package com.wetao.module_homework;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tstudy.blepenlib.BlePenStreamManager;
import com.tstudy.blepenlib.constant.CommonUtil;
import com.tstudy.blepenlib.data.BleDevice;
import com.tstudy.blepenlib.data.CoordinateInfo;
import com.wetao.lib_common.AppConfig;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseListResponse;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsReq;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsReq_vo;
import com.wetao.lib_common.bean.request.SmallTestCommitReq;
import com.wetao.lib_common.bean.request.SmallTestCommitReq_questionList;
import com.wetao.lib_common.bean.response.CommitAssistantAnswerResp;
import com.wetao.lib_common.bean.response.GetAssistantQuestionList;
import com.wetao.lib_common.bean.response.GetAssistantQuestionList2;
import com.wetao.lib_common.bean.response.GetAssistantQuestionList_grids;
import com.wetao.lib_common.bean.vo.PictureMore;
import com.wetao.lib_common.bean.vo.QuestionNumShow;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.AssistantExam;
import com.wetao.lib_common.greendao.model.AssistantQuestion;
import com.wetao.lib_common.greendao.model.ExamListen;
import com.wetao.lib_common.greendao.model.PagePicture;
import com.wetao.lib_common.greendao.model.PagePictureGrid;
import com.wetao.lib_common.greendao.model.PenOffLineGridInfo;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.tsdBlePen.TsdPenUtil;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BitmapUtil;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MultiClickUtil;
import com.wetao.lib_common.utils.MyDividerItemDecoration;
import com.wetao.lib_common.utils.QuestionTypeUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.WrapContentLinearLayoutManager;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.lib_common.view.graffiti.GraffitiOnTouchGestureListener;
import com.wetao.lib_common.view.graffiti.GraffitiTouchDetector;
import com.wetao.lib_common.view.graffiti.GraffitiView;
import com.wetao.lib_common.view.graffiti.IGraffitiTouchDetector;
import com.wetao.module_homework.adapter.HomeworkNumAdapter;
import com.wetao.module_homework.adapter.HomeworkObjectAdapter;
import com.wetao.module_homework.contract.HomeworkCodeActivityCon;
import com.wetao.module_homework.presenter.HomeworkCodeActivityPre;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = ConstantArouter.PATH_HOMEWORK_CODEACTIVITY)
public class HomeworkCodeActivity extends BaseActivity<HomeworkCodeActivityCon.View, HomeworkCodeActivityPre>
        implements HomeworkCodeActivityCon.View {

    private static final int DOODLE_SAVE_TYPE_SWITCH = 101;
    private static final int DOODLE_SAVE_TYPE_SUBMIT = 102;
    private static final int DOODLE_SAVE_TYPE_EXIT = 103;

    @Autowired
    boolean mIsTupu = false;
    @Autowired
    int mExamId;
    @Autowired
    int mOutlineContentId;

    @BindView(R2.id.ibtn_h_prev)
    ImageButton ibtn_h_prev;
    @BindView(R2.id.ibtn_h_next)
    ImageButton ibtn_h_next;
    @BindView(R2.id.btn_next_question)
    Button btn_next_question;
    @BindView(R2.id.tv_title)
    TextView tv_title;
    private ConcurrentLinkedQueue<CoordinateInfo> mOffLineDots = new ConcurrentLinkedQueue();
    private List<PagePicture> mPagePictureListByAddress; //防止频繁被创建，
    private List<AssistantQuestion> mQuestionListByExam;
    private boolean mIsUploadTrans = false; //是否上传透明图片
    private boolean mIsHttping = false;
    private boolean mIsSwitchBitmaping;
    private boolean mIsSaveingPic = false; //为了解决图片保存过程中去切换图片
    private boolean mIsSubmiting;
    private boolean mIsPenMoveOk = false;
    private boolean mIsNextExamOk = false; //是否允许点击第二个课时切换课时
    private boolean mIsGridNull = false; //格子为空时做弹框提示
    private CoordinateInfo mCurDot;//当前正在绘制的点；
    private AssistantExam mCurExam;
    private List<PagePicture> mCurExamPagePictures;
    private PagePicture mCurPagePicture; //当前点绘制在那张图片上
    private PagePicture mCurPagePicture_temp; //不允许切换课时时做临时存储
    private PagePictureGrid mCurPagePictureGrid; //不准，经常为null
    private AssistantQuestion mCurQuestion;
    private boolean mIsLastQuestion; //是否是最后一题
    private int mMaxCountLine = 0; //一行最多放多少个
    private int mNumfirstVisible;
    private int mNumfirstComplete;
    private int mNumlastVisible;
    private int mNumlastComplete;
    private float mTemp_x = 0f; //暂存转换后的坐标
    private float mTemp_y = 0f;
    private float mTemp_w = 0f; //暂存转换后的坐标
    private float mTemp_h = 0f;
    private float m_tran_x = 0f; //题目移动的x坐标
    private float m_tran_y = 0f; //题目移动的y坐标
    private float m_tran_again_x = 0f; //题目移动后，再移动坐标
    private float m_tran_again_y = 0f; //题目移动后，再移动坐标
    private boolean mIsTran_x = false; //是否允许滚动；
    private boolean mIsTran_y = false; //是否允许滚动；
    private boolean mIsPenDown = false; //处理点码移动和弹起时的前提条件试，要有按下
    private int mOssCount = 0;
    private List<OssParams> mOssParamsList = new ArrayList<>();
    private boolean mIsSubmitSuccess = true;
    private Map<Integer, String> oss_qId_pic = new HashMap<>();

    @BindView(R2.id.rv_num)
    RecyclerView rv_num;
    @BindView(R2.id.rv_object)
    RecyclerView rv_object;
    private HomeworkNumAdapter mHomeworkNumAdapter;
    private HomeworkObjectAdapter mHomeworkObjectAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private MyDividerItemDecoration mDividerItemDecoration;

    @BindView(R2.id.fl_doodle)
    FrameLayout fl_doodle;
    private String mPicFilePath_b;
    private String mPicFilePath_f;
    private String mPicFilePath_c;
    private Bitmap mDoodle_b = null;
    private Bitmap mDoodle_f = null;
    private float mScale = 1f;
    private boolean mIsLoadImg_b_end = false;
    private boolean mIsLoadImg_f_end = false;
    private int mDoodleSaveType = 0;
    private int mPic_w;
    private int mPic_h;

    private GraffitiView mGraffitiView;
    private GraffitiOnTouchGestureListener mGraffitiTouchGestureListener;

    private int mMoudle;
    private AssistantExam mSmallTestData;
    private int mSmallTest_question_index = -1;
    private int mSmallTest_picture_index = -1;
    private int mSmallTest_picture_index_temp = -1;
    private int mSmallTest_pictureGrid_index = -1;
    private boolean mSmallTest_isGoodDot = false;
    private boolean mSmallTest_TeacherSubmit = false;

    private boolean mIsPenAutoConnect = false; //判断蓝牙笔是否要自动连接
    private boolean mIsPenAutoConnecting = false;//判断已经搜索到蓝牙笔，正在自动连接

    private CommitAssistantAnswerResp mCommitResult;

    @BindView(R2.id.ll_h)
    LinearLayout ll_h;
    @BindView(R2.id.iv_no_data)
    ImageView iv_no_data;
    @BindView(R2.id.tv_no_data)
    TextView tv_no_data;
    private boolean mIsClickable = false;

    private Disposable mDisposable_scroll;

    private Bitmap mSmall_bitmap = null;

    private List<String> noDataPageAddressList = new ArrayList<>();

    private boolean mToDetail = false;

    @Override
    public int getLayoutId() {
        return R.layout.homework_code_activity;
    }

    @Override
    public boolean getIsBindTsdService() {
        return true;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return mTsdListener;
    }

    @Override
    public HomeworkCodeActivityPre createPresenter() {
        return new HomeworkCodeActivityPre(this);
    }

    @Override
    public HomeworkCodeActivityCon.View createView() {
        return this;
    }

    @Override
    public void setTsdServiceConnected() {
        super.setTsdServiceConnected();

        mMoudle = mTsdServiceBinder.on_getmModule();
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            if(mSmallTestData == null) {
                mHomeworkObjectAdapter.setmMoudle(mMoudle);
                getPresenter().queryClassroomTestQuestionList(ComUtil.getHashmapByStr(
                        new String[]{"examPublishId", "studentExamId"},
                        new String[]{mTsdServiceBinder.on_getmSmallTest_command().getPublishId().intValue() + "", ""}), false, false);
            }
        }else if(mIsTupu) {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_CODE_TUPU_INTO, null));
            mMoudle = mTsdServiceBinder.on_getmModule();
        } else {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_CODE_INTO, null));
            mMoudle = mTsdServiceBinder.on_getmModule();
        }
        LogUtils.i("获取模式mMoudle = " + mMoudle);
    }

    @Override
    public void init() {
        //禁止息屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().register(this);
        LogUtils.e("++++++++++++================init==============");
        initRecyclerView();
        mSmall_bitmap = BitmapUtil.ReadBitmapById_4444(this, R.drawable.doodle_bk);
    }

    @Override
    protected void onDestroy() {
        deleteFileBackSmallTestView();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if(mIsTupu) {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_CODE_TUPU_OUT, null));
        } else if(mMoudle != TsdService.MODULE_SMALLTEST_DOT) {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_CODE_OUT, null));
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        if(mCurExam == null && mMoudle != TsdService.MODULE_SMALLTEST_DOT) {
            finish();
        } else {
            exitActivity();
        }
    }

    @OnClick({R2.id.iv_back,
                R2.id.btn_next_question,
                R2.id.ibtn_h_prev,
                R2.id.ibtn_h_next,
    })
    public void onClickView(View v) {
        int id = v.getId();
        if(mIsHttping || mIsSwitchBitmaping || mIsSaveingPic) {
            ToastUtil.initToast("正在保存图片，请稍后操作");
            return;
        }
        if(id == R.id.iv_back) {
            if(mCurExam == null && mMoudle != TsdService.MODULE_SMALLTEST_DOT) {
                finish();
            } else {
                exitActivity();
            }
        }
        if(!mIsClickable) {
            LogUtils.e("mIsClickable === false");
            return;
        }
        if(id == R.id.btn_next_question) {
            //mTouchGestureListener.setDoodleTranslationXY(-200f, -300f);
            if(mIsLastQuestion) {
                //提交作答
                if (!ComUtil.isNetworkConnected()) {
                    ToastUtil.initToast(getString(R.string.network_disconnect_error));
                    return;
                }

                if (mMoudle == TsdService.MODULE_SMALLTEST_DOT && !mTsdServiceBinder.on_getmJoinRoom() ){
                    ToastUtil.initToast(getString(R.string.network_disconnect_error));
                    return;
                }

                int num = getNoAnswerNum();
                if(num > 0) {
                    DialogXUtil.customDialogShow("你有" + num + "道题未进行作答，\r\n确定提交作答吗？" , "提交", "取消", new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {
                            clickSubmit_pre();
                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                } else {
                    DialogXUtil.customDialogShow("确定要提交吗？" , "提交", "取消", new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {
                            mSmallTest_TeacherSubmit = false;
                            clickSubmit_pre();
                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                }
            } else {
                //下一题
                AssistantQuestion question = mHomeworkNumAdapter.getNextQuestion();
                int temp = mHomeworkNumAdapter.getNextPosition();
                if(temp >= 0) {
                    if(temp < mNumfirstComplete) {
                        prevLine();
                    } else if(temp > mNumlastComplete) {
                        nextLine();
                    }
                }
                if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                    clickChoiceQuestion_smallTest(question);
                } else {
                    List<PagePictureGrid>grids = DBUtils.getInstance(HomeworkCodeActivity.this).getPagePictureGridByQuestionId(question.getQuestionId());
                    if(grids == null || grids.size() == 0) {
                        LogUtils.e("数据库错误，通过题目id找不到格子");
                    } else {
                        PagePictureGrid gd = grids.get(0);
                        clickChoiceQuestion(gd, question);
                    }
                }
            }
        } else if(id == R.id.ibtn_h_prev) {
            prevLine();
        } else if(id == R.id.ibtn_h_next) {
            nextLine();
        }
    }


    @Override
    public void getAssistantQuestionListResult(BaseListResponse<GetAssistantQuestionList> response) {
        mIsHttping = false;
        if(response.getData() != null && response.getData().size() > 0) {
            for(GetAssistantQuestionList item : response.getData()) {
                if(item.getExamId() == null) {
                    mIsPenMoveOk = false;
                    showNoData(true);
                    continue;
                }
                AssistantExam assistantExam = DBUtils.getInstance(this).getAssistantExamByExamId(item.getExamId());
                if(assistantExam == null) {
                    LogUtils.i("m1: 数据空教辅为null，重新将http数据写入数据库");
                    long assistantExamId =  DBUtils.getInstance(this).insertAssistantExam(new AssistantExam(null, item.getExamId(), item.getExamName(), item.getPublishId(), ComUtil.getStringDate(), null));
                    Map<Integer, Long> picId_dbId = new HashMap<>();
                    for(GetAssistantQuestionList2 item2 : item.getQuestionList()) {
                        if(item2.getGridsVoList() == null) {
                            DBUtils.getInstance(this).deleteAssistantExamByExamid(item.getExamId());
                            if(!mIsGridNull) {
                                mIsGridNull = true;
                                ToastUtil.initToast("获取格子出错");
                            }
                            mIsPenMoveOk = false;
                            showNoData(true);
                            return;
                        }
                        DBUtils.getInstance(this).insertAssistantQuestion(new AssistantQuestion(null, item2.getQuestionId(), item2.getQuestionNo(),
                                item2.getQuestionScore(), item2.getQuestionContent(),
                                item2.getQuestion(), StringUtil.strlistToString(item2.getOptions(), "###"),
                                item2.getExplain(), StringUtil.strlistToString(item2.getAnswers(), "###"),
                                item2.getQuestionType(), item2.getIsSingle(),
                                item2.getQuestionScreen(), item2.getScreenType(), item2.getScreenId(),
                                item2.getListeningUrl(), item2.getDuration(), item2.getChapterId(),
                                item2.getQuestionDetailId(), null, null, false, assistantExamId));
                        if(!StringUtil.isEmpty(item2.getListeningUrl())) {
                            ExamListen examListen = DBUtils.getInstance(this).getExamListenByUrl(item2.getListeningUrl());
                            if(examListen == null) {
                                DBUtils.getInstance(this).insertExamListen(new ExamListen(null, item2.getListeningUrl(), item2.getDuration(), item2.getQuestionId() + "", assistantExamId));
                            } else if(!StringUtil.strToList(examListen.getQuesitonIdArr(), ",").contains(item2.getQuestionId() + "")) {
                                examListen.setQuesitonIdArr(examListen.getQuesitonIdArr() + "," + item2.getQuestionId());
                                DBUtils.getInstance(this).updateExamListen(examListen);
                            }
                        }
                        //Map<Integer, Long> picId_dbId = new HashMap<>();
                        for(GetAssistantQuestionList_grids item3 : item2.getGridsVoList()) {
                            if(picId_dbId.containsKey(item3.getPictureId().intValue())) {
                                long dbId = picId_dbId.get(item3.getPictureId().intValue());
                                DBUtils.getInstance(this).insertPagePictureGrid(new PagePictureGrid(null, item2.getQuestionId(), item2.getQuestionNo(), item3.getStartX(), item3.getStartY(), item3.getEndX(), item3.getEndY(), item2.getQuestionType(), dbId));
                            } else {
                                PagePicture pagePicture = DBUtils.getInstance(this).getPagePictureByPictureId(item3.getPictureId());
                                if(pagePicture == null) {
                                    boolean isMore = false;
                                    boolean isHttp = false;
                                    PictureMore pictureMore = new PictureMore();
                                    PagePicture pic = new PagePicture(null, item3.getPictureUrl(), item3.getBigPicWidth(), item3.getBigPicHeight(),
                                            item3.getPictureId(), item3.getBookId(), item3.getPageNumber(), item3.getSectionNo(), item3.getOwnerNo(),
                                            item3.getPageserial(), isMore, isHttp, pictureMore.startX_L, pictureMore.startY_L, pictureMore.endX_L, pictureMore.endY_L,
                                            pictureMore.startX_R, pictureMore.startY_R, pictureMore.endX_R, pictureMore.endY_R, null, 1, assistantExamId);
                                    long dbId = DBUtils.getInstance(this).insertPagePicture(pic);

                                    picId_dbId.put(item3.getPictureId().intValue(), dbId);
                                    DBUtils.getInstance(this).insertPagePictureGrid(new PagePictureGrid(null, item2.getQuestionId(), item2.getQuestionNo(), item3.getStartX(), item3.getStartY(), item3.getEndX(), item3.getEndY(), item2.getQuestionType(), dbId));
                                } else {
                                    picId_dbId.put(pagePicture.getPictureId().intValue(), pagePicture.getId());
                                    DBUtils.getInstance(this).insertPagePictureGrid(new PagePictureGrid(null, item2.getQuestionId(), item2.getQuestionNo(), item3.getStartX(), item3.getStartY(), item3.getEndX(), item3.getEndY(),item2.getQuestionType(), pagePicture.getId()));
                                }
                            }
                        }
                    }
                } else {
                    LogUtils.i("m1: 有这个教辅");
                }
            }

            //对当前页重新设置
            List<PagePicture> list = DBUtils.getInstance(this).getPagePictureByPageserial(mCurDot.pageAddress);
            if(list == null || list.size() == 0) {
                LogUtils.e("m1: 数据库出错了");
            } else if(list.size() == 1) {
                list.get(0).setIsHttp(true);
                DBUtils.getInstance(this).updatePagePicture(list.get(0));
                //设置当前图片
                mCurPagePicture_temp = list.get(0);
                if(!mIsNextExamOk && mCurExam != null && mCurPagePicture_temp != null) {
                    //不允许下课时条件一
                    AssistantExam exam = DBUtils.getInstance(this).getAssistantExamById(mCurPagePicture_temp.getAssistantExamId());
                    if(exam != null && mCurExam.getExamId().intValue() != exam.getExamId().intValue()) {
                        mIsPenMoveOk = false;
                        ToastUtil.initToast("作答中不允许切换课时~");
                        return;
                    }
                }
                mCurPagePicture = mCurPagePicture_temp;
            } else {
                //一页两课时
                for(PagePicture item : list) {
                    List<PagePictureGrid> grids = item.getGridList();
                    PictureMore pictureMore = new PictureMore();
                    for(PagePictureGrid item2 : grids) {
                        pictureMore.setTemp1(item2.getStartX(), item2.getStartY(), item2.getEndX(), item2.getEndY(), item.getBigPicWidth(), item.getBigPicHeight());
                    }
                    pictureMore.setTemp2(item.getBigPicWidth(), item.getBigPicHeight());
                    item.setIsHttp(true);
                    item.setIsMore(true);
                    item.setStartX_L(pictureMore.startX_L);
                    item.setStartY_L(pictureMore.startY_L);
                    item.setEndX_L(pictureMore.endX_L);
                    item.setEndY_L(pictureMore.endY_L);
                    item.setStartX_R(pictureMore.startX_R);
                    item.setStartY_R(pictureMore.startY_R);
                    item.setEndX_R(pictureMore.endX_R);
                    item.setEndY_R(pictureMore.endY_R);
                    DBUtils.getInstance(this).updatePagePicture(item);
                }

                //设置当前图片
                mCurPagePicture_temp = choicePagePicture(mCurDot, list);
                if(!mIsNextExamOk && mCurExam != null && mCurPagePicture_temp != null) {
                    //不允许下课时条件一
                    AssistantExam exam = DBUtils.getInstance(this).getAssistantExamById(mCurPagePicture_temp.getAssistantExamId());
                    if(exam != null && mCurExam.getExamId().intValue() != exam.getExamId().intValue()) {
                        mIsPenMoveOk = false;
                        ToastUtil.initToast("作答中不允许切换课时~");
                        return;
                    }
                }
                mCurPagePicture = mCurPagePicture_temp;

            }

            if(mCurPagePicture == null || mCurPagePicture.getPictureId() == null) {
                LogUtils.e("m1: okhttp请求数据后，还是有问题");
                return;
            }
            switchPicData_real_pre();
        } else {
            LogUtils.e("m1: 返回数据为空");
            if(mCurExam == null) {
                showNoData(true);
            }
            mIsPenMoveOk = false;
        }
    }

    @Override
    public void getAssistantQuestionListFailed() {
        mIsHttping = false;
        mIsPenMoveOk = false;

        if(mCurExam == null) {
            showNoData(true);
        }
    }

    @Override
    public void commitAssistantAnswerResult(BaseResponse<CommitAssistantAnswerResp> resp) {
        /*if(true){
            return;
        }*/
        mCommitResult = resp.getData();
        deleteDataAndFile();
    }

    @Override
    public void commitAssistantAnswerFailed(int code) {
        //ToastUtil.initToast("提交作业失败");
        mIsSubmiting = false;
        mIsSubmitSuccess = false;
        //DialogXUtil.waitDialogDismiss();
        isSubmitSuccess();

        if(code == Constants.HTTP_ERROR.HTTP_TOKEN_OUT) {
            delayToOutLogin();
        }
    }

    @Override
    public void queryClassroomTestQuestionListResult(BaseResponse<GetAssistantQuestionList> resp) {
        if(resp.getData() != null) {
            GetAssistantQuestionList resp_data = resp.getData();
            initSmallTestData(resp_data);
        } else {
            LogUtils.e("m1: 返回数据为空");
        }
    }

    @Override
    public void queryClassroomTestQuestionListFailed() {
        finish();
    }

    private void prevLine() {
        if(mNumfirstComplete - mMaxCountLine >= 0) {
            rv_num.scrollToPosition(mNumfirstComplete - mMaxCountLine);
        } else {
            rv_num.scrollToPosition(0);
        }
    }

    private void nextLine() {
        if(mNumlastComplete + mMaxCountLine >= mHomeworkNumAdapter.getItemCount()) {
            rv_num.scrollToPosition(mHomeworkNumAdapter.getItemCount() - 1);
        } else {
            rv_num.scrollToPosition(mNumlastComplete + mMaxCountLine);
        }
    }

    private void delayToOutLogin() {
        Observable.timer(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        DialogUtil.getInstance().reLoginDialog(HomeworkCodeActivity.this, "账号已在其他设备登录，\r\n请重新登录");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void exitActivity() {
        DialogXUtil.customDialogShow(mMoudle == TsdService.MODULE_SMALLTEST_DOT ? "退出后将无法再继续作答，\r\n确定放弃作答吗？" : "退出会缓存作答数据，\r\n确定要退出作答吗？", "确定", "取消", new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {
                if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                    EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_BACK_FINISH,null));
                    finish();
                    return;
                }
                if(mGraffitiView != null) {
                    mDoodleSaveType = DOODLE_SAVE_TYPE_EXIT;
                    mGraffitiView.save();
                } else {
                    finish();
                }
            }

            @Override
            public void onListenDialogCancel() {

            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }

    private TsdService.OnDataReceiveListener mTsdListener = new TsdService.OnDataReceiveListener() {
        @Override
        public void onFinish() {
            finish();
        }

        @Override
        public void onErrTsdPen(int code, String msg) {
            if(mIsPenAutoConnect) {
                mIsPenAutoConnect = false;
                mIsPenAutoConnecting = false;
                DialogXUtil.waitDialogDismiss();
                showNoPenConnectDialog(true);
            }
        }

        @Override
        public void onRefreshScan(boolean isScaning) {
            if(mIsPenAutoConnect && !mIsPenAutoConnecting && !isScaning) {
                mIsPenAutoConnect = false;
                mIsPenAutoConnecting = false;
                DialogXUtil.waitDialogDismiss();
                showNoPenConnectDialog(true);
            }
        }

        @Override
        public void onAddDevice(BleDevice bleDevice) {
            if(mIsPenAutoConnect) {
                String mac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
                if(bleDevice.getMac().equals(mac)) {
                    mIsPenAutoConnecting = true;
                    //mTsdServiceBinder.on_stopScan();//取消搜索
                    mTsdServiceBinder.on_penConnect(bleDevice);
                }
            }

        }

        @Override
        public void onPenConnectStatus(int code, BleDevice bleDevice) {
            if(mIsPenAutoConnect) {
                if (code == TsdService.CONN_PEN_SUCCESS) {
                    BlePenStreamManager.getInstance().getPenInfo();
                    /*mIsPenAutoConnect = false;
                    mIsPenAutoConnecting = false;
                    DialogXUtil.waitDialogDismiss();
                    BlePenStreamManager.getInstance().setRealtimeMode();
                    DialogXUtil.customDialogShow("自动重连成功！", "", "好的", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });*/

                } else if (code == TsdService.CONN_PEN_FAIL || code == TsdService.CONN_PEN_DIS) {
                    mIsPenAutoConnect = false;
                    mIsPenAutoConnecting = false;
                    DialogXUtil.waitDialogDismiss();
                    showNoPenConnectDialog(true);
                }
            }
        }

        @Override
        public void onGetPenInfo(int batteryPercent, int memoryPercent, int memoryByteNum) {
            LogUtils.i("作答界面获得笔的信息：batteryPercent:" + batteryPercent + ", memoryPercent:" + memoryPercent + ", memoryByteNum:" + memoryByteNum);
            if(!mIsPenAutoConnect) {
                return;
            }
            mIsPenAutoConnect = false;
            mIsPenAutoConnecting = false;
            DialogXUtil.waitDialogDismiss();
            if(memoryByteNum > 0) {
                DialogXUtil.customDialogShow("笔有离线数据，\r\n请转到智能笔界面", "", "好的", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {
                    }

                    @Override
                    public void onListenDialogCancel() {
                        ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                    }

                    @Override
                    public void onListenDialogClose() {

                    }
                });
            } else {
                BlePenStreamManager.getInstance().setRealtimeMode();
                DialogXUtil.customDialogShow("自动重连成功！", "", "好的", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {

                    }

                    @Override
                    public void onListenDialogCancel() {

                    }

                    @Override
                    public void onListenDialogClose() {

                    }
                });
            }
        }

        @Override
        public void onCoordDraw(CoordinateInfo coordinateInfo) {
            if(coordinateInfo == null) {
                return;
            }
            if(mIsSubmiting) {
                return;
            }
            if(mMoudle == TsdService.MODULE_SMALLTEST_DOT && mSmallTestData == null) {
                return;
            }
            if(noDataPageAddressList.contains(coordinateInfo.pageAddress)) {
                return;
            }
            if((mMoudle == TsdService.MODULE_HOMEWORK_CODE || mIsTupu)
                    && mCurExamPagePictures != null
                    && mCurExamPagePictures.size() > 0) {
                boolean isSameExame = false;
                for(PagePicture item : mCurExamPagePictures) {
                    if(coordinateInfo.pageAddress.equals(item.getPageserial())) {
                        isSameExame = true;
                        break;
                    }
                }
                if(!isSameExame) {
                    if(coordinateInfo.state == TsdService.PEN_DOWN_MESSAGE) {
                        ToastUtil.initToast("作答中不允许切换课时~");
                    }
                    return;
                }
            }
            mOffLineDots.offer(coordinateInfo);
            nextDots();
        }

        @Override
        public void onTeacherExitSmallTest() {
            if(tv_no_data.getVisibility() == View.VISIBLE) {
                EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_BACK_FINISH,null));
                finish();
            } else if(!mIsSubmiting) {
                mSmallTest_TeacherSubmit = true;
                clickSubmit_pre();
            } else {
                //如果正在上传，直接返回
                if (mIsSubmiting)return;
                DialogXUtil.customDialogDismiss();
                EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_BACK_FINISH,null));
                finish();
            }
        }
    };

    private void showNoData(boolean isNo) {
        if(isNo) {
            if(ll_h.getVisibility() == View.VISIBLE) {
                ll_h.setVisibility(View.GONE);
                iv_no_data.setVisibility(View.VISIBLE);
                tv_no_data.setVisibility(View.VISIBLE);
                rv_object.setVisibility(View.GONE);
                btn_next_question.setVisibility(View.GONE);
            }
            if(mCurDot != null
                    && !noDataPageAddressList.contains(mCurDot.pageAddress)
                    && ComUtil.isNetworkConnected()) {
                noDataPageAddressList.add(mCurDot.pageAddress);
            }
        } else {
            if(ll_h.getVisibility() == View.GONE) {
                ll_h.setVisibility(View.VISIBLE);
                iv_no_data.setVisibility(View.GONE);
                tv_no_data.setVisibility(View.GONE);

                rv_object.setVisibility(View.GONE);
                btn_next_question.setVisibility(View.VISIBLE);
            }
        }
    }
    private void nextDots() {
        if(mCurExam == null/* && mOffLineDots.isEmpty()*/) {
            //showNoData(true);
        } else {
            showNoData(false);
        }

        if (!mIsHttping && !mIsSwitchBitmaping && !mOffLineDots.isEmpty()) {
            mCurDot = mOffLineDots.poll();
            if(mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
                mIsPenDown = true;
            } else if(mCurDot.state == TsdService.PEN_UP_MESSAGE) {
                mIsPenDown = false;
            }
            if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                analysisDots_smallTest();
            } else {

                analysisDots();
            }

        }
    }

    private void analysisDots() {
        if(mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            mIsPenMoveOk = true;
            if(mCurPagePicture == null) {
                switchPicData();
            } else {
                if(mCurDot.pageAddress.equals(mCurPagePicture.getPageserial())) {
                    //说明这一页是点击过的。==== 这一页点击过

                    if((mCurPagePicture.getIsMore())) {
                        //有多个课时，判断那张图片
                        mPagePictureListByAddress = DBUtils.getInstance(this).getPagePictureByPageserial(mCurDot.pageAddress);
                        //找到图片
                        PagePicture picture = choicePagePicture(mCurDot, mPagePictureListByAddress);
                        if (picture == null) return;
                        if(mCurPagePicture.getPictureId().intValue() == picture.getPictureId().intValue()) {
                            //没有切换图片，客观题和主观题都要写字，
                            //判断客观题还是主观题，显示和隐藏是有差别的，是否切换题号
                            //改作答状态
                            //滚动图片
                            //绘制图片
                            switchQuestion();
                        } else {
                            //切换图片
                            switchPicData();
                        }
                    } else {
                        //没有切换图片，客观题和主观题都要写字，
                        //判断客观题还是主观题，显示和隐藏是有差别的，是否切换题号
                        //改作答状态
                        //滚动图片
                        //绘制图片

                        switchQuestion();
                    }
                } else {
                    //切换图片
                    switchPicData();
                }
            }
        } else {
            if(mCurPagePicture == null) {
                LogUtils.e("m1: 丢弃的移动或弹起点2");
            } else {
                //绘制图片
                if(mIsPenMoveOk) {
                    drawBitmap();
                }
            }
        }
    }

    private void switchPicData() {
        //切换图片数据
        //先找到这一张图片
        mPagePictureListByAddress = DBUtils.getInstance(this).getPagePictureByPageserial(mCurDot.pageAddress);
        if(mPagePictureListByAddress == null || mPagePictureListByAddress.size() == 0) {
            //数据库中没有，http请求
            mIsHttping = true;
            if(mIsTupu) {
                getPresenter().getCourseQuestionList(ComUtil.getHashmapByStr(
                        new String[]{"examId", "outlineContentId"},
                        new String[]{mExamId + "", mOutlineContentId + ""}), false, false);
            } else {
                getPresenter().getAssistantQuestionList(ComUtil.getHashmapByStr(
                        new String[]{"bookId ", "pageNumber", "ownerNo", "sectionNo", "pageserial", "type"},
                        new String[]{null, null, null, null, mCurDot.pageAddress, "2"}), false, false);
            }
        } else if(mPagePictureListByAddress.size() > 1) {
        //} else if(getAllIsHttp()) {
            if(!getAllIsHttp()) {
                toHttpData();
                return;
            }
            //数据库至少有两个，只考虑一页最多两个课时，这一页点击过

            //找到图片
            mCurPagePicture_temp = choicePagePicture(mCurDot, mPagePictureListByAddress);
            if(!mIsNextExamOk && mCurExam != null && mCurPagePicture_temp != null) {
                //不允许下课时条件一
                AssistantExam exam = DBUtils.getInstance(this).getAssistantExamById(mCurPagePicture_temp.getAssistantExamId());
                if(exam != null && mCurExam.getExamId().intValue() != exam.getExamId().intValue()) {
                    mIsPenMoveOk = false;
                    ToastUtil.initToast("作答中不允许切换课时~");
                    return;
                }
            }
            mCurPagePicture = mCurPagePicture_temp;
            if(mCurPagePicture == null || mCurPagePicture.getPictureId() == null) {
                LogUtils.e("m1: 有两张图片，却没找到，有问题");
                if(mCurExam == null) {
                    showNoData(true);
                }
                mIsPenMoveOk = false;
                return;
            }
            //切题图片
            //将图片滚动到题目坐标位置
            //是否切换课时
            //是否切换题号
            //绘制图片
            switchPicData_real_pre();
        } else {
            if(mPagePictureListByAddress.get(0).getIsHttp()) {
            //if(getAllIsHttp()) {
                //这一页点击过

                //找到图片
                mCurPagePicture_temp = mPagePictureListByAddress.get(0);
                if(!mIsNextExamOk && mCurExam != null && mCurPagePicture_temp != null) {
                    //不允许下课时条件一
                    AssistantExam exam = DBUtils.getInstance(this).getAssistantExamById(mCurPagePicture_temp.getAssistantExamId());
                    if(exam != null && mCurExam.getExamId().intValue() != exam.getExamId().intValue()) {
                        mIsPenMoveOk = false;
                        ToastUtil.initToast("作答中不允许切换课时~");
                        return;
                    }
                }
                mCurPagePicture = mCurPagePicture_temp;
                if(mCurPagePicture == null || mCurPagePicture.getPictureId() == null) {
                    LogUtils.e("m1: 有一张图片，却为null，有问题");
                    if(mCurExam == null) {
                        showNoData(true);
                    }
                    mIsPenMoveOk = false;
                    return;
                }

                //切题图片
                //将图片滚动到题目坐标位置
                //是否切换课时
                //是否切换题号
                //绘制图片
                switchPicData_real_pre();

            } else {
                //这一页没有点击过，http请求
                toHttpData();
            }
        }
    }

    private void toHttpData() {
        mIsHttping = true;
        if(mIsTupu) {
            getPresenter().getCourseQuestionList(ComUtil.getHashmapByStr(
                    new String[]{"examId", "outlineContentId"},
                    new String[]{mExamId + "", mOutlineContentId + ""}), false, false);
        } else {
            getPresenter().getAssistantQuestionList(ComUtil.getHashmapByStr(
                    new String[]{"bookId ", "pageNumber", "ownerNo", "sectionNo", "pageserial", "type"},
                    new String[]{null, null, null, null, mCurDot.pageAddress, "2"}), false, false);
        }
    }

    private boolean getAllIsHttp() {
        for(PagePicture item: mPagePictureListByAddress) {
            if(!item.getIsHttp()) {
                return false;
            }
        }
        return true;
    }

    private void switchPicData_real_pre() {
        mIsSwitchBitmaping = true;
        if(mIsSaveingPic) {
            return;
        }
        DialogXUtil.waitDialogShow("正在切换图片，请稍后~");
        if(mGraffitiView != null) {
            mDoodleSaveType = DOODLE_SAVE_TYPE_SWITCH;
            mGraffitiView.save();
        } else {
            switchPicData_real();
        }
    }

    private void switchPicData_real() {
        switchExam();
        switchBitmap();
    }

    private PagePicture choicePagePicture(CoordinateInfo dot, List<PagePicture> picList) {
        for(PagePicture item : picList) {
            float x = TsdPenUtil.getRealX(dot.coordX, item.getBigPicWidth());
            float y = TsdPenUtil.getRealY(dot.coordY, item.getBigPicHeight());
            if(x > item.getStartX_L().floatValue() && x < item.getEndX_L().floatValue() && y > item.getStartY_L().floatValue() && y < item.getEndY_L().floatValue()) {
                return  item;
            }
            if(x > item.getStartX_R().floatValue() && x < item.getEndX_R().floatValue() && y > item.getStartY_R().floatValue() && y < item.getEndY_R().floatValue()) {
                return  item;
            }
        }
        return null;
    }

    private void switchExam(){
        LogUtils.i("m1: 切换课时");
        //切课时之前，会保存数据，清空UI
        AssistantExam exam = DBUtils.getInstance(this).getAssistantExamById(mCurPagePicture.getAssistantExamId());
        if(exam == null) {
            LogUtils.e("m1: AssistantExamB数据库出错");

            mIsPenMoveOk = false;
            return;
        }

        if(mCurExam != null && mCurExam.getExamId().intValue() == exam.getExamId().intValue()) {
            //不需要切换课时
            //切换题号
            switchQuestion();
        } else {
            //切换课时
            /*if(mCurExam != null){
                //不允许中途切换课时，如果允许，那么就注释掉这个条件的代码
                ToastUtil.initToast("请退出作答后，再点击切换作答");
                mIsPenMoveOk = false;
                return;
            }*/
            mCurExam = exam;
            mCurExamPagePictures = mCurExam.getPictureList();
            tv_title.setText(mCurExam.getExamName() == null ? "" : StringUtil.replaceAmp(mCurExam.getExamName()));

            //切换课时，需要考虑重置一些参数
            //mCurQuestion = null;

            mQuestionListByExam = mCurExam.getQuestionList();
            initQuestionNumShow();
            mIsClickable = true;
            //切换题号
            switchQuestion();
        }
    }

    private void initQuestionNumShow() {
        LogUtils.i("m1: 重置题号列表");
        int start = 0;
        int end = 0;
        List<QuestionNumShow> questionList = new ArrayList<>();
        QuestionNumShow objectShow = null;
        List<AssistantQuestion> aqList = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            aqList = mSmallTestData.getQuestionList();
        } else {
            aqList = mQuestionListByExam;
        }
        for(AssistantQuestion item : aqList) {
            if(QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                //客观题
                if(start == 0) {
                    start = item.getQuestionNo();
                    objectShow = new QuestionNumShow();
                    objectShow.getQuestionList().add(item);
                } else {
                    end = item.getQuestionNo();
                    objectShow.getQuestionList().add(item);
                }
                //最后一题是客观题
                if(item.getQuestionId().intValue() == aqList.get(aqList.size() - 1).getQuestionId().intValue()) {
                    if(end == 0) {
                        objectShow.setStrNum(start + "");
                    } else {
                        objectShow.setStrNum(start + "-" + end);
                    }
                    questionList.add(objectShow);
                }
            } else {
                if(objectShow != null) {
                    if(end == 0) {
                        objectShow.setStrNum(start + "");
                    } else {
                        objectShow.setStrNum(start + "-" + end);
                    }
                    questionList.add(objectShow);
                }

                //主观题
                QuestionNumShow numShow = new QuestionNumShow();
                numShow.setStrNum(item.getQuestionNo() + "");
                numShow.getQuestionList().add(item);
                questionList.add(numShow);

                objectShow = null;
                start = 0;
                end = 0;

            }
        }
        mHomeworkNumAdapter.updateData(questionList);
    }


    private void switchQuestion() {
        //判断是否切换题号

        PagePictureGrid grid = mCurPagePictureGrid;
        mCurPagePictureGrid = null;
        PagePictureGrid tempGrid = null;
        for(PagePictureGrid item : mCurPagePicture.getGridList()) {
            float x = TsdPenUtil.getRealX(mCurDot.coordX, mCurPagePicture.getBigPicWidth());
            float y = TsdPenUtil.getRealY(mCurDot.coordY, mCurPagePicture.getBigPicHeight());
            if(tempGrid == null
                    /*&& item.getQuestionId().intValue() == mCurExam.getQuestionList().get(0).getQuestionId().intValue()*/
                    && item.getQuestionId().intValue() == mCurPagePicture.getGridList().get(0).getQuestionId().intValue()
            ) {
                tempGrid = item; //第一次进入，点击在题外用
            }
            if(x > item.getStartX().floatValue() && x < item.getEndX().floatValue() && y > item.getStartY().floatValue() && y < item.getEndY().floatValue()) {
                mCurPagePictureGrid = item;
                break;
            }
        }
        if(mCurQuestion == null && mCurPagePictureGrid == null) {
            //第一次进入，并且点击在题外，默认第一题
            mCurPagePictureGrid = tempGrid;
        }

        if(mCurPagePictureGrid  == null) {
            LogUtils.e("m1: 点击到题的格子外, 不做操作");
            //绘制在格子外的涂鸦是否显示
            //drawBitmap();
        } else {
            AssistantQuestion question = DBUtils.getInstance(this).getAssistantQuestionByQuestionId(mCurPagePictureGrid.getQuestionId());
            if(question == null) {
                LogUtils.e("m1: 数据库中，没有找到这一题");
            } else if(mIsSwitchBitmaping || mCurQuestion == null
                    || mCurQuestion.getQuestionId().intValue() != question.getQuestionId().intValue()
                    || (grid != null && mCurPagePictureGrid.getId().longValue() != grid.getId().longValue())
            ) {
                //正在切换图片，一定要重新切换试题
                setCurQuestion(question);
            } else {
                LogUtils.i("m1: 是同一题号作答");
                //绘制图片

                drawBitmap();
            }
        }
    }

    private void setCurQuestion(AssistantQuestion question) {
        mCurQuestion = question;
        if(QuestionTypeUtil.isSubjectQuestion(mCurQuestion.getQuestionType())) {
            //mCurQuestion.setMyAnswer("1"); //主观题设置1，认为这一题已经作答
            DBUtils.getInstance(this).updateAssistantQuestion(mCurQuestion);
            if(mTsdServiceBinder.on_getmBleDevice() == null) {
                showNoPenConnectDialog(false);
            }
        }

        LogUtils.i("m1: 切换题号");
        refreshQustionNumUI();
        if(QuestionTypeUtil.isObjectQuestion(mCurQuestion.getQuestionType())) {
            rv_object.setVisibility(View.VISIBLE);
            fl_doodle.setVisibility(View.INVISIBLE);
        } else {
            rv_object.setVisibility(View.GONE);
            fl_doodle.setVisibility(View.INVISIBLE);
        }

        if(!mIsSwitchBitmaping) {
            //没有切图片直接滚动图片
            scrollBitmap();
            //滚动完图片后绘制图片
            drawBitmap();
        } else {
            LogUtils.i("m1: 正在切换图片，等切换图片后再滚动图片");
        }
    }

    private void refreshQustionNumUI() {
        mHomeworkNumAdapter.setmQuestionId(mCurQuestion.getQuestionId().intValue());
    }

    private void switchBitmap() {
        downLoadImg();
    }

    private void scrollBitmap() {

        if(mCurPagePictureGrid == null) {
            LogUtils.e("mCurPagePictureGrid == null");
            return;
        }


        m_tran_x = mCurPagePictureGrid.getStartX().floatValue();
        m_tran_y = mCurPagePictureGrid.getStartY().floatValue();
        m_tran_again_x = 0;
        m_tran_again_y = 0;
        mTemp_w = mCurPagePictureGrid.getEndX().floatValue() - mCurPagePictureGrid.getStartX().floatValue();
        mTemp_h = mCurPagePictureGrid.getEndY().floatValue() - mCurPagePictureGrid.getStartY().floatValue();
        mIsTran_x = false;
        mIsTran_y = false;
        if(mTemp_w > fl_doodle.getWidth()) {
            mIsTran_x = true;
        }
        if(mTemp_h > fl_doodle.getHeight()) {
            mIsTran_y = true;
        }
        LogUtils.i("m1: 滚动坐标到x=" + m_tran_x + ", y = " + m_tran_y + ", mTemp_w = " + mTemp_w + ", mTemp_h = " + mTemp_h);

        mGraffitiTouchGestureListener.setGraffitiTranslationXY(-m_tran_x, -m_tran_y);
        mGraffitiView.refreshMaskView(mTemp_w, mTemp_h, mGraffitiView.getWidth(), mGraffitiView.getHeight());


        if(QuestionTypeUtil.isObjectQuestion(mCurQuestion.getQuestionType())) {
            rv_object.setVisibility(View.VISIBLE);
            fl_doodle.setVisibility(View.INVISIBLE);
        } else {
            rv_object.setVisibility(View.GONE);
            fl_doodle.setVisibility(View.VISIBLE);
        }

    }

    private void drawBitmap() {
        if(mCurDot == null) {
            //小测点阵教辅，点击第一次进入acitivity时就是null
            LogUtils.e("mCurDot == null 小测点阵教辅，点击第一次进入acitivity时就是null");
            return;
        }

        if (mGraffitiTouchGestureListener == null) {
            LogUtils.e("mGraffitiTouchGestureListener == null ");
            nextDots();
            return;
        }


        if(mSmallTestData != null && (mSmallTest_picture_index >= mSmallTestData.getPictureList().size()
                || mSmallTest_pictureGrid_index >= mSmallTestData.getPictureList().get(mSmallTest_picture_index).getGridList().size()) ) {
            LogUtils.e("数组越界！！！");
            nextDots();
            return;
        }

        mTemp_x = TsdPenUtil.getRealX(mCurDot.coordX, mPic_w) - m_tran_x - m_tran_again_x;
        mTemp_y = TsdPenUtil.getRealY(mCurDot.coordY, mPic_h) - m_tran_y - m_tran_again_y;

        PagePictureGrid grid = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            grid = mSmallTestData.getPictureList().get(mSmallTest_picture_index).getGridList().get(mSmallTest_pictureGrid_index);
        } else {
            grid = mCurPagePictureGrid;
        }
        if(mCurDot.state == TsdService.PEN_DOWN_MESSAGE
                && grid != null
                && (grid.getEndY().floatValue() - grid.getStartY().floatValue() > fl_doodle.getHeight()
                    || grid.getEndX().floatValue() - grid.getStartX().floatValue() > fl_doodle.getWidth())) {
            boolean isT= false;
            if(mTemp_y > fl_doodle.getHeight()
                    && m_tran_again_y != grid.getEndY().floatValue() - grid.getStartY().floatValue() - fl_doodle.getHeight()) {
                isT = true;
                m_tran_again_y = mTemp_y + m_tran_again_y;
                if(m_tran_again_y > grid.getEndY().floatValue() - grid.getStartY().floatValue() - fl_doodle.getHeight()) {
                    m_tran_again_y = grid.getEndY().floatValue() - grid.getStartY().floatValue() - fl_doodle.getHeight();
                }

            } else if(mTemp_y < 0 && m_tran_again_y != 0) {
                isT = true;
                m_tran_again_y =TsdPenUtil.getRealY(mCurDot.coordY, mPic_h) - m_tran_y;
                if(m_tran_again_y < 0) {
                    m_tran_again_y = 0;
                }
            }

            if(mTemp_x > fl_doodle.getWidth()
                    && m_tran_again_x != grid.getEndX().floatValue() - grid.getStartX().floatValue() - fl_doodle.getWidth()) {
                isT = true;
                m_tran_again_x = mTemp_x + m_tran_again_x;
                if(m_tran_again_x > grid.getEndX().floatValue() - grid.getStartX().floatValue() - fl_doodle.getWidth()) {
                    m_tran_again_x = grid.getEndX().floatValue() - grid.getStartX().floatValue() - fl_doodle.getWidth();
                }

            } else if(mTemp_x < 0 && m_tran_again_x != 0) {
                isT = true;
                m_tran_again_x =TsdPenUtil.getRealX(mCurDot.coordX, mPic_w) - m_tran_x;
                if(m_tran_again_x < 0) {
                    m_tran_again_x = 0;
                }
            }


            if(isT) {

                mGraffitiTouchGestureListener.setGraffitiTranslationXY(-m_tran_x - m_tran_again_x, -m_tran_y - m_tran_again_y);
                //mGraffitiView.refreshMaskView(mTemp_w, mTemp_h, mGraffitiView.getWidth(), mGraffitiView.getHeight());

                mTemp_x = TsdPenUtil.getRealX(mCurDot.coordX, mPic_w) - m_tran_x -  m_tran_again_x;
                mTemp_y = TsdPenUtil.getRealY(mCurDot.coordY, mPic_h) - m_tran_y - m_tran_again_y;

            }
        }

        //更新主观题是否已作答，只有移动时才做判断，原因手动切题也会加入点数据
        if(mCurDot.state == TsdService.PEN_COODINAT_MESSAGE) {
            if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                if(QuestionTypeUtil.isSubjectQuestion(mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionType())
                        && !mSmallTestData.getQuestionList().get(mSmallTest_question_index).getIsSubjectMyAns()) {
                    mSmallTestData.getQuestionList().get(mSmallTest_question_index).setIsSubjectMyAns(true);
                }
            } else {
                if(mCurQuestion != null
                        && QuestionTypeUtil.isSubjectQuestion(mCurQuestion.getQuestionType())
                        && !mCurQuestion.getIsSubjectMyAns()) {
                    mCurQuestion.setIsSubjectMyAns(true);
                    DBUtils.getInstance(this).updateAssistantQuestion(mCurQuestion);
                }
            }
        }



        LogUtils.i("m1: 绘制坐标：coordX = " + mCurDot.coordX + ", coordY = " + mCurDot.coordY + ", mPic_w = " + mPic_w + ", mPic_h = " + mPic_h);
        LogUtils.i("m1: 绘制坐标：mTemp_x = " + mTemp_x + ", mTemp_y = " + mTemp_y);

        if (mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            mGraffitiTouchGestureListener.r_onDown(mTemp_x, mTemp_y);
            mGraffitiTouchGestureListener.r_onScrollBegin(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_COODINAT_MESSAGE) {
            mGraffitiTouchGestureListener.r_onScroll(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_UP_MESSAGE) {
            mGraffitiTouchGestureListener.r_onScrollEnd(mTemp_x, mTemp_y);
        }


        nextDots();
    }

    private void initRecyclerView() {
        mLayoutManager = new WrapContentLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mHomeworkNumAdapter = new HomeworkNumAdapter();
        rv_num.setLayoutManager(mLayoutManager);
        mDividerItemDecoration = new MyDividerItemDecoration(this, LinearLayoutManager.HORIZONTAL, R.drawable.divider_mileage_voice_class);
        //rv_num.addItemDecoration(mDividerItemDecoration);
        rv_num.setItemAnimator( new DefaultItemAnimator());
        rv_num.setAdapter(mHomeworkNumAdapter);
        ((HomeworkNumAdapter)mHomeworkNumAdapter).setOnItemClickListener(new HomeworkNumAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LogUtils.i("onItemClick--" + position);
                if(mIsHttping || mIsSwitchBitmaping || mIsSaveingPic) {
                    ToastUtil.initToast("正在保存图片，请稍后操作");
                    return;
                }
                AssistantQuestion question = mHomeworkNumAdapter.getQuestion(position);
                if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                    clickChoiceQuestion_smallTest(question);
                    /*for(int i = 0; i < mSmallTestData.getQuestionList().size(); i++) {
                        if(mSmallTestData.getQuestionList().get(i).getQuestionId().intValue() == question.getQuestionId()) {
                            mSmallTest_question_index = i;
                            mSmallTest_picture_index_temp = mSmallTest_picture_index;
                            mSmallTest_picture_index = -1;
                            break;
                        }
                    }
                    switchQuestion_smallTest();*/
                } else {
                    List<PagePictureGrid> grids = DBUtils.getInstance(HomeworkCodeActivity.this).getPagePictureGridByQuestionId(question.getQuestionId());
                    if (grids == null || grids.size() == 0) {
                        LogUtils.e("数据库错误，通过题目id找不到格子");
                    } else {
                        PagePictureGrid gd = grids.get(0);
                        clickChoiceQuestion(gd, question);
                    }
                }

            }

            @Override
            public void onPositionChange(int position) {
                mHomeworkObjectAdapter.updateData(mHomeworkNumAdapter.getCurPostionData());
            }

            @Override
            public void onIsLastQuestion(boolean isLastQuestion) {
                mIsLastQuestion = isLastQuestion;
                if(mIsLastQuestion) {
                    btn_next_question.setText("提交作答");
                } else {
                    btn_next_question.setText("下一题");
                }
            }
        });
        rv_num.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                LogUtils.i("m1: onScrolled dx = " + dx + ", dy = " + dy);

                LinearLayoutManager layoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
                if(layoutManager != null) {
                    mNumfirstVisible  = layoutManager.findFirstVisibleItemPosition();
                    mNumfirstComplete = layoutManager.findFirstCompletelyVisibleItemPosition();
                    mNumlastVisible  = layoutManager.findLastVisibleItemPosition();
                    mNumlastComplete = layoutManager.findLastCompletelyVisibleItemPosition();
                    LogUtils.i("m1: onScrolled -- FirstVisible = " + mNumfirstVisible + ", FirstComplete = " + mNumfirstComplete +", LastVisible = " +  mNumlastVisible +", LastComplete = " +  mNumlastComplete);
                    //HomeworkNumAdapter.NumHolder numHolder = (HomeworkNumAdapter.NumHolder)rv_num.findViewHolderForAdapterPosition(firstVisible);
                    if(mNumlastComplete - mNumfirstComplete > mMaxCountLine) {
                        mMaxCountLine = mNumlastComplete - mNumfirstComplete;
                    }
                    if(mNumfirstComplete == 0) {
                        ibtn_h_prev.setImageResource(R.drawable.common_rc_left_s);
                        ibtn_h_prev.setClickable(false);
                    } else {
                        ibtn_h_prev.setImageResource(R.drawable.common_rc_left_n);
                        ibtn_h_prev.setClickable(true);
                    }

                    if(mNumlastComplete == mHomeworkNumAdapter.getItemCount() - 1) {
                        ibtn_h_next.setImageResource(R.drawable.common_rc_right_s);
                        ibtn_h_next.setClickable(false);
                    } else {
                        ibtn_h_next.setImageResource(R.drawable.common_rc_right_n);
                        ibtn_h_next.setClickable(true);
                    }
                }
                super.onScrolled(recyclerView, dx, dy);
            }
        });


        mLayoutManager = new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mHomeworkObjectAdapter = new HomeworkObjectAdapter(this);
        rv_object.setLayoutManager(mLayoutManager);
        mDividerItemDecoration = new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, R.drawable.divider_mileage_voice_class);
        //rv_object.addItemDecoration(mDividerItemDecoration);
        rv_object.setItemAnimator( new DefaultItemAnimator());
        rv_object.setAdapter(mHomeworkObjectAdapter);
        ((HomeworkObjectAdapter)mHomeworkObjectAdapter).setOnItemClickListener(new HomeworkObjectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LogUtils.i("onItemClick--" + position);
            }
        });
    }

    private void clickChoiceQuestion(PagePictureGrid gd, AssistantQuestion question) {
        PagePicture pc = DBUtils.getInstance(HomeworkCodeActivity.this).getPagePictureById(gd.getPagePictureId().longValue());
        //if(pc != null && pc.getPictureId().intValue() != mCurPagePicture.getPictureId().intValue()) {
            float d_x = TsdPenUtil.picToDotX(gd.getStartX().floatValue() + 5, pc.getBigPicWidth().intValue());
            float d_y = TsdPenUtil.picToDotY(gd.getStartY().floatValue() + 5,  pc.getBigPicHeight().intValue());
            LogUtils.i("格子坐标转成纸的dot坐标: x:" + d_x + ", y:" +d_y);
            CoordinateInfo ci_down = new CoordinateInfo(TsdService.PEN_DOWN_MESSAGE, pc.getPageserial(), (int)d_x, (int)d_y, 0, 0, 0, false, 0, 0);
            CoordinateInfo ci_up = new CoordinateInfo(TsdService.PEN_UP_MESSAGE, pc.getPageserial(), (int)d_x, (int)d_y, 0, 0, 0, false, 0, 0);
            mOffLineDots.offer(ci_down);
            mOffLineDots.offer(ci_up);
            nextDots();
        /*} else {
            mCurPagePictureGrid = gd;
            setCurQuestion(question);
        }*/
    }

    private void downLoadImg() {
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            mPic_w = mSmallTestData.getPictureList().get(mSmallTest_picture_index).getBigPicWidth().intValue();
            mPic_h = mSmallTestData.getPictureList().get(mSmallTest_picture_index).getBigPicHeight().intValue();
        } else {
            mPic_w = mCurPagePicture.getBigPicWidth().intValue();
            mPic_h = mCurPagePicture.getBigPicHeight().intValue();
        }

        mDoodle_b = null;
        mDoodle_f = null;
        mIsLoadImg_b_end = false;
        mIsLoadImg_f_end = false;
        int pictureId = 0;
        String pDir = "";
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            pictureId = mSmallTestData.getPictureList().get(mSmallTest_picture_index).getPictureId();
            pDir = "smalltest_noline";
        } else {
            pictureId = mCurPagePicture.getPictureId();
            pDir = "offline";
        }

        mPicFilePath_b = FileUtils.getPicFilePath(this, pDir + File.separator + "b", "" + pictureId, "");
        mPicFilePath_f = FileUtils.getPicFilePath(this, pDir + File.separator + "f", "" + pictureId, "");
        mPicFilePath_c = FileUtils.getPicFilePath(this, pDir + File.separator + "c", "" + pictureId, "");


        LogUtils.i("m2: mPicFilePath_b = " + mPicFilePath_b);
        LogUtils.i("m2: mPicFilePath_f = " + mPicFilePath_f);
        LogUtils.i("m2: mPicFilePath_c = " + mPicFilePath_c);

        String url_b = "";
        File file_b = new File(mPicFilePath_b);
        File file_c = new File(mPicFilePath_c);

        if(file_c.exists()) {
            url_b = mPicFilePath_c;
        } else if(file_b.exists()) {
            url_b = mPicFilePath_b;
        } else {
            if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                url_b = mSmallTestData.getPictureList().get(mSmallTest_picture_index).getPictureUrl();
            } else {
                url_b = mCurPagePicture.getPictureUrl();
            }
        }


        final String url_b_temp = url_b;

		mDoodle_b = null;
        mDoodle_f = null;
        fl_doodle.removeAllViews();
        mGraffitiView = null;
        mGraffitiTouchGestureListener = null;

        Glide.with(this).asBitmap().load(url_b_temp).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        LogUtils.e("m1:Glde图片-成功  = " + url_b_temp + ", threadName = " + Thread.currentThread().getName());
                        mDoodle_b = resource;
                        mIsLoadImg_b_end = true;
                        if(!url_b_temp.equals(mPicFilePath_b) && !url_b_temp.equals(mPicFilePath_c)) {
                            //从网上下载，需要存在本地
                            String path_b = mPicFilePath_b;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    FileUtils.saveBitmap(resource, path_b);
                                }
                            }).start();
                        }
                        //initDoodleData_pre();
                        downLoadImg_f();
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        LogUtils.e("m1:Glde图片-失败  = " + url_b_temp + ", threadName = " + Thread.currentThread().getName());
                        //图片已经损坏要处理
                        if(url_b_temp.equals(mPicFilePath_b)) {
                            LogUtils.e("图片有问题，删除这一张图片：" + mPicFilePath_b);
                            file_b.delete();
                            downLoadImg();
                        } else if(url_b_temp.equals(mPicFilePath_c)) {
                            LogUtils.e("图片有问题，删除这一张图片：" + mPicFilePath_c);
                            file_c.delete();
                            downLoadImg();
                        } else {
                            mIsLoadImg_b_end = true;
                            //initDoodleData_pre();
                            downLoadImg_f();
                        }
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void downLoadImg_f() {
        File file_f = new File(mPicFilePath_f);
        if(file_f.exists()) {
            Glide.with(this).asBitmap().load(mPicFilePath_f).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            LogUtils.e("m1:Glde图片-成功  = " + mPicFilePath_f + ", threadName = " + Thread.currentThread().getName());
                            mDoodle_f = resource;
                            mIsLoadImg_f_end = true;
                            initDoodleData_pre();
                        }

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            super.onLoadFailed(errorDrawable);
                            LogUtils.e("m1:Glde图片-失败  = " + mPicFilePath_f + ", threadName = " + Thread.currentThread().getName());
                            //图片已经损坏要处理
                            LogUtils.e("图片有问题，删除这一张图片：" + mPicFilePath_f);
                            file_f.delete();
                            downLoadImg_f();
                            /*mIsLoadImg_f_end = true;
                            initDoodleData_pre();*/
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        } else {
            mDoodle_f = resizeImage(mSmall_bitmap, mPic_w, mPic_h);
            mIsLoadImg_f_end = true;
            initDoodleData_pre();
        }
    }

    public Bitmap resizeImage(Bitmap bitmap, int width, int height) {

        int bmpWidth = bitmap.getWidth();
        int bmpHeight = bitmap.getHeight();

        float scaleWidth = ((float) width) / bmpWidth;
        float scaleHeight = ((float) height) / bmpHeight;

        LogUtils.i("m1:宽放大倍数：" + scaleWidth +  ", bmpWidth = " + bmpWidth + ", width = " + width);
        LogUtils.i("m1:高放大倍数：" + scaleHeight);

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        return Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    }


    private void initDoodleData_pre() {
        if(mIsLoadImg_b_end && mIsLoadImg_f_end) {
            if(mDoodle_b == null) {
                LogUtils.e("出错了，背景图为null");
                mIsSwitchBitmaping = false;
                DialogXUtil.waitDialogDismiss();

                //tv_no_data.setText("加载背景图片失败，请退出作答后，检查网络~");
                tv_no_data.setText("加载背景图片失败，检查网络~");
                showNoData(true);
            } else {
                showNoData(false);
                /*int p_w = mDoodle_b.getWidth();
                int v_w = fl_doodle.getWidth();
                if(p_w > v_w) {
                    mScale = 1.0f * v_w / p_w;
                } else {
                    mScale = 1f;
                }
                LogUtils.i("m1: 倍数 mScale:" + mScale + ", p_w:" + p_w + ", v_w:" + v_w);
                if(mScale < 1) {

                    Matrix matrix = new Matrix();
                    matrix.postScale(mScale, mScale); //长和宽放大缩小的比例
                    mDoodle_b = Bitmap.createBitmap(mDoodle_b, 0, 0, mDoodle_b.getWidth(), mDoodle_b.getHeight(), matrix, true);
                    if(mDoodle_f != null) {
                        mDoodle_f = Bitmap.createBitmap(mDoodle_f, 0, 0, mDoodle_f.getWidth(), mDoodle_f.getHeight(), matrix, true);
                    }
                    LogUtils.i("m1: 倍数 后:" + ", 宽:" + mDoodle_b.getWidth() + ", 高:" + mDoodle_b.getHeight());
                }*/

                initGraffitiData();

            }
        }
    }

    private void rxjava_disposable_scroll() {
        if(mDisposable_scroll != null && !mDisposable_scroll.isDisposed()) {
            mDisposable_scroll.dispose();
            mDisposable_scroll = null;
        }
    }

    private void rxjava_interval_scroll() {
        Observable.interval(10, 100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable_scroll = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());

                        mGraffitiTouchGestureListener.setGraffitiTranslationXY(-m_tran_x - m_tran_again_x, -m_tran_y - m_tran_again_y);

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void initGraffitiData() {
        fl_doodle.removeAllViews();
        mGraffitiView = new GraffitiView(this, mDoodle_b, mDoodle_f, true, false, new GraffitiView.IGraffitiViewListener(){

            @Override
            public void onSaved(List<Bitmap> bitmaps) {
                LogUtils.i("m1:涂鸦保存成功"  + ", threadName = " + Thread.currentThread().getName());
                /*if(mScale < 1) {
                    Matrix matrix = new Matrix();
                    matrix.postScale(1.0f/mScale, 1.0f/mScale);
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                }*/

                String path_c = mPicFilePath_c;
                String path_f = mPicFilePath_f;
                mIsSaveingPic = true;
                if(mDoodleSaveType == DOODLE_SAVE_TYPE_EXIT) {
                    DialogXUtil.waitDialogShow("正在退出，请稍后~");
                }
                Observable.create(new ObservableOnSubscribe<Integer>() {
                    @Override
                    public void subscribe(final ObservableEmitter<Integer> emitter) throws Exception {
                        LogUtils.i("========================= subscribe currentThread name: " + Thread.currentThread().getName());
                        FileUtils.saveBitmap(bitmaps.get(0), path_c);
                        FileUtils.saveBitmap(bitmaps.get(1), path_f);

                        emitter.onNext(1);
                        emitter.onComplete();

                    }
                }).subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Integer>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                //创建只运行1次，执行顺序1 -- main
                                LogUtils.i("========================= onSubscribe currentThread name: " + Thread.currentThread().getName());

                            }

                            @Override
                            public void onNext(Integer o) {
                                //运行多次 执行顺序3 -- thread
                                LogUtils.i("========================= onNext currentThread name: " + Thread.currentThread().getName());
                                mIsSaveingPic = false;
                                if(mDoodleSaveType == DOODLE_SAVE_TYPE_SUBMIT) {

                                    if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                                        clickSubmit(bitmaps.get(0));
                                    } else {
                                        //透明图片
                                        if(mIsUploadTrans) {
                                            clickSubmit(bitmaps.get(1));
                                        } else {
                                            clickSubmit(bitmaps.get(0));
                                        }
                                    }

                                }  else if(mDoodleSaveType == DOODLE_SAVE_TYPE_EXIT) {
                                    DialogXUtil.waitDialogDismiss();
                                    finish();
                                } else {
                                    if (mIsSwitchBitmaping) {
                                        if (mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                                            switchPicData_smallTest();
                                        } else {
                                            switchPicData_real_pre();
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                //运行1次  -- thread
                                LogUtils.i("========================= onError currentThread name: " + Thread.currentThread().getName() + "--" + e.getMessage());

                            }

                            @Override
                            public void onComplete() {
                                //运行1次  -- thread
                                LogUtils.i("========================= onComplete currentThread name: " + Thread.currentThread().getName());

                            }
                        });

                 if(mDoodleSaveType == DOODLE_SAVE_TYPE_SWITCH) {
                    if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                        switchQuestion_smallTest();
                        switchBitmap_smallTest();
                    } else {
                        switchPicData_real();
                    }
                }
            }
        });
        mGraffitiTouchGestureListener = new GraffitiOnTouchGestureListener(mGraffitiView, new GraffitiOnTouchGestureListener.IGraffitiOnTouchGestureListener() {
            @Override
            public void onTest() {

            }
            @Override
            public void onCallScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                LogUtils.i("m1:滚动手指：distanceX: " + distanceX + ", distanceY:" + distanceY);
                if((mIsTran_x || mIsTran_y) && mOffLineDots.isEmpty() && !mIsPenDown) {
                    PagePictureGrid grid = null;
                    if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                        grid = mSmallTestData.getPictureList().get(mSmallTest_picture_index).getGridList().get(mSmallTest_pictureGrid_index);
                    } else {
                        grid = mCurPagePictureGrid;
                    }
					if(grid == null) {
                        return;
                    }
                    if(mIsTran_y) {
                        m_tran_again_y = m_tran_again_y + distanceY;
                        if (m_tran_again_y > grid.getEndY().floatValue() - grid.getStartY().floatValue() - fl_doodle.getHeight()) {
                            m_tran_again_y = grid.getEndY().floatValue() - grid.getStartY().floatValue() - fl_doodle.getHeight();
                        } else if (m_tran_again_y < 0) {
                            m_tran_again_y = 0;
                        }
                    }
                    if(mIsTran_x) {
                        m_tran_again_x = m_tran_again_x + distanceX;
                        if (m_tran_again_x > grid.getEndX().floatValue() - grid.getStartX().floatValue() - fl_doodle.getWidth()) {
                            m_tran_again_x = grid.getEndX().floatValue() - grid.getStartX().floatValue() - fl_doodle.getWidth();
                        } else if (m_tran_again_x < 0) {
                            m_tran_again_x = 0;
                        }
                    }

                    mGraffitiTouchGestureListener.setGraffitiTranslationXY(-m_tran_x -  m_tran_again_x, -m_tran_y- m_tran_again_y);
                    //mGraffitiView.refreshMaskView(mTemp_w, mTemp_h, mGraffitiView.getWidth(), mGraffitiView.getHeight());
                }
            }
        });

        IGraffitiTouchDetector detector = new GraffitiTouchDetector(this, mGraffitiTouchGestureListener);
        mGraffitiView.setDefaultTouchDetector(detector);

        mGraffitiTouchGestureListener.setSupportScale(false); //禁止放大缩小
        setSupportDoodle(false);
        setSupportTrans(false);
        mGraffitiTouchGestureListener.setTouchType(GraffitiOnTouchGestureListener.TOUCH_TYPE_ALL);

        //graffitiView.setStartXy(true);
        mGraffitiView.setColor(Color.BLACK);
        mGraffitiView.setIsDrawableOutside(false);
        mGraffitiView.setSize(4);

        fl_doodle.addView(mGraffitiView);

        delayToDot(300);

    }

    private boolean isGraffitiSave() {
        if(mGraffitiView != null && mGraffitiView.getItemCount() > 0) {
            return true;
        }
        return false;
    }



    private void setSupportDoodle(boolean isSupport) {

        if (mGraffitiTouchGestureListener != null) {
            mGraffitiTouchGestureListener.setSupportGraffiti(isSupport);
        }

    }

    private void setSupportTrans(boolean isSupport) {

        if (mGraffitiTouchGestureListener != null) {
            mGraffitiTouchGestureListener.setSupportTrans(isSupport);
        }
    }

    private void delayToDot(int time) {
        Observable.timer(time, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        DialogXUtil.waitDialogDismiss();
                        mIsSwitchBitmaping = false;
                        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                            scrollBitmap_smallTest();
                            drawBitmap_smallTest();
                        } else {
                            scrollBitmap();
                            drawBitmap();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void clickSubmit_pre() {
        DialogXUtil.waitDialogShow("正在上传作答...");
        if(mGraffitiView != null) {
            mIsSubmiting = true;
            mDoodleSaveType = DOODLE_SAVE_TYPE_SUBMIT;
            mGraffitiView.save();
        } else {
            clickSubmit(null);
        }
    }

    private void clickSubmit(Bitmap bitmap) {
        clipPic(bitmap);
    }
    private void submitData_pre() {
        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        CommitAssistantQuestionsReq req = new CommitAssistantQuestionsReq();
        AssistantExam exam = mCurExam;

        req.setExamId(exam.getExamId());
        req.setStudentId(studentId);
        req.setBeginTime(exam.getBeginTime());
        req.setFinishTime(ComUtil.getStringDate());
        List<AssistantQuestion> qList = DBUtils.getInstance(this).getAssistantQuestionByAssistantExamId(exam.getId());


        if(qList == null) {
            LogUtils.e("提交时获得的题目为空， 出错了");
            mIsSubmiting = false;
            DialogXUtil.waitDialogDismiss();
            return;
        }
        List<CommitAssistantQuestionsReq_vo> vList = new ArrayList<>();
        for(AssistantQuestion item : qList) {
            CommitAssistantQuestionsReq_vo vo = new CommitAssistantQuestionsReq_vo();
            vo.setQuestionId(item.getQuestionId());
            vo.setQuestionType(item.getQuestionType());
            if(QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                vo.setAnswerType(1);
                vo.setAnswerContent(item.getMyAnswer());
            } else {
                vo.setAnswerType(2);
                vo.setAnswerContent(item.getOssPath());
            }
            vList.add(vo);
        }
        req.setQuestionList(vList);
        String json = JsonUtils.toJson(req);
        getPresenter().commitAssistantAnswer(json, false, false);

    }

    private void deleteFileBackSmallTestView() {
        String pDir = "smalltest_noline";
        String path_b_dir = FileUtils.getPicDirPath(this, pDir + File.separator + "b");
        String path_f_dir = FileUtils.getPicDirPath(this, pDir + File.separator + "f");
        String path_c_dir = FileUtils.getPicDirPath(this, pDir + File.separator + "c");
        String path_t_dir = FileUtils.getPicDirPath(this, pDir + File.separator + "t");
        File f_b = new File(path_b_dir);
        FileUtils.deleteDirWihtFile(f_b); //清空文件夹
        File f_f = new File(path_f_dir);
        FileUtils.deleteDirWihtFile(f_f); //清空文件夹
        File f_c = new File(path_c_dir);
        FileUtils.deleteDirWihtFile(f_c); //清空文件夹
        File f_t = new File(path_t_dir);
        FileUtils.deleteDirWihtFile(f_t); //清空文件夹
    }

    private void deleteDataAndFile() {
        String pDir = "";
        AssistantExam exam = null;
        List<PagePicture> pList = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            exam = mSmallTestData;
            pList = exam.getPictureList();
            pDir = "smalltest_noline";
        } else {
            exam = DBUtils.getInstance(this).getAssistantExamByExamId(mCurExam.getExamId());
            pList = DBUtils.getInstance(this).getPagePictureByAssistantExamId(exam.getId());
            pDir = "offline";
        }


        for(PagePicture item : pList) {
            String path_b = FileUtils.getPicFilePath(this, pDir + File.separator + "b", "" + item.getPictureId(), "");
            String path_f = FileUtils.getPicFilePath(this, pDir + File.separator + "f", "" + item.getPictureId(), "");
            String path_c = FileUtils.getPicFilePath(this, pDir + File.separator + "c", "" + item.getPictureId(), "");
            File f_b = new File(path_b);
            File f_f = new File(path_f);
            File f_c = new File(path_c);
            if(f_b.exists()) {
                f_b.delete();
            }
            if(f_f.exists()) {
                f_f.delete();
            }
            if(f_c.exists()) {
                f_c.delete();
            }
            if(mMoudle != TsdService.MODULE_SMALLTEST_DOT) {
                DBUtils.getInstance(this).deletePagePictureGridByPagePictureId(item.getId());
            }

            /*一页两课时，完成一课时后，再点击混乱*/
            List<PagePicture> sameList = DBUtils.getInstance(this).getPagePictureByPageserial(item.getPageserial());
            if(sameList != null) {
                for(PagePicture sameItem : sameList) {
                    if(item.getPictureId().intValue() != sameItem.getPictureId().intValue()) {
                        sameItem.setIsHttp(false);
                        DBUtils.getInstance(this).updatePagePicture(sameItem);
                    }
                }
            }
        }
        if(mMoudle != TsdService.MODULE_SMALLTEST_DOT) {
            DBUtils.getInstance(this).deletePagePictureByAssistantExamId(exam.getId());
            DBUtils.getInstance(this).deleteAssistantQuestionByAssistantExamId(exam.getId());
            DBUtils.getInstance(this).deleteExamListenByAssistantExamId(exam.getId());
            DBUtils.getInstance(this).deleteAssistantExamByExamid(exam.getExamId());

            //离线在线同步用

            DBUtils.getInstance(this).updatePenOffLineGridInfoByExamid(exam.getExamId());
            //DBUtils.getInstance(this).deletePenOffLineGridInfoByExamid(exam.getExamId());

            DBUtils.getInstance(this).clearBuffer();
        }

        //ToastUtil.initToast("提交作业成功");
        //mIsSubmiting = false;
        DialogXUtil.waitDialogDismiss();
        isSubmitSuccess();
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_ANSWER_SUBMIT_SUCCESS, null));

        if(mSmallTest_TeacherSubmit) {
            mIsSubmiting = false;
            finish();
            return;
        }
        DialogXUtil.customDialogShow(mSmallTest_TeacherSubmit?"老师主动结束作答，\r\n自动提交成功！":"恭喜，提交成功！", "", mMoudle == TsdService.MODULE_SMALLTEST_DOT ? "好的" : "查看作答详情", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {

            }

            @Override
            public void onListenDialogCancel() {
                if(mToDetail) {
                    return;
                }
                MultiClickUtil.isFastClick();
                mToDetail = true;
                mIsSubmiting = false;
                if(mMoudle != TsdService.MODULE_SMALLTEST_DOT) {
                    if (mCommitResult != null) {
                        ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_DETAILACTIVITY)
                                .withString("examName", mCurExam.getExamName())
                                .withInt("examId", mCurExam.getExamId())
                                .withInt("publishId", mCommitResult.getExamPublishId())
                                .withInt("studentExamId", mCommitResult.getStudentExamId())
                                .navigation();
                    }
                }
                finish();
            }

            @Override
            public void onListenDialogClose() {

            }
        });

    }

    private void clipPic(Bitmap bitmap){
        mOssCount = 0;
        mOssParamsList.clear();
        Map<Integer, String> qId_pic = new HashMap<>(); //一个questionId对应多个图片，图片之间用逗号隔开，编号从0开始
        String pDir = "";
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            pDir = "smalltest_noline";
        } else {
            pDir = "offline";
        }
        String path_t_dir = FileUtils.getPicDirPath(this, pDir + File.separator + "t");
        File f_t = new File(path_t_dir);
        FileUtils.deleteDirWihtFile(f_t); //清空文件夹
        //将主观题的各个格子截成小图
        AssistantExam exam = null;
        PagePicture curPagePicture = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            exam = mSmallTestData;
            if(exam == null) {
                return;
            }
            curPagePicture = exam.getPictureList().get(mSmallTest_picture_index);
        } else {
            exam = mCurExam;
            curPagePicture = mCurPagePicture;
        }
        Bitmap bitmap_t = null;
        if(exam == null) {
            LogUtils.e("出错了，exam = null");
            finish();
            return;
        }
        for(PagePicture item1 : exam.getPictureList()) {
            if(item1.getPictureId().intValue() == curPagePicture.getPictureId().intValue()
               && bitmap != null) {
                bitmap_t = bitmap;
            } else {
                String path_c = null;
                if(mMoudle != TsdService.MODULE_SMALLTEST_DOT && mIsUploadTrans) {
                    path_c = FileUtils.getPicFilePath(this, pDir+ File.separator + "f", "" + item1.getPictureId(), "");
                } else {
                    path_c = FileUtils.getPicFilePath(this, pDir+ File.separator + "c", "" + item1.getPictureId(), "");
                }
                File f_c = new File(path_c);
                if(f_c.exists()) {
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(path_c);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    bitmap_t  = BitmapFactory.decodeStream(fis);
                }
            }
            if(bitmap_t != null) {
                for (PagePictureGrid item2 : item1.getGridList()) {
                    AssistantQuestion qst = null;
                    if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                        for(AssistantQuestion q : exam.getQuestionList()) {
                            if(q.getQuestionId().intValue() == item2.getQuestionId().intValue()) {
                                qst = q;
                                break;
                            }
                        }
                    } else {
                        qst = DBUtils.getInstance(this).getAssistantQuestionByQuestionId(item2.getQuestionId().intValue());
                    }
                    if(qst == null) {
                        LogUtils.e("这一题没有找到");
                        continue;
                    }
                    if(QuestionTypeUtil.isObjectQuestion(qst.getQuestionType()) || !subjectHavMyAns(exam.getExamId(), qst.getIsSubjectMyAns())) {
                        LogUtils.e("这一题是客观题，不截图, 或者这一题没有涂鸦，不截图");
                        continue;
                    }
                    Bitmap clip_bitmap = Bitmap.createBitmap(bitmap_t, item2.getStartX().intValue(), item2.getStartY().intValue(), item2.getEndX().intValue() - item2.getStartX().intValue(), item2.getEndY().intValue() - item2.getStartY().intValue());
                    int num = 0;
                    String picStr = "";
                    if(qId_pic.containsKey(item2.getQuestionId().intValue())) {
                        picStr = qId_pic.get(item2.getQuestionId().intValue());
                        List<String> picList = StringUtil.strToList(picStr, ",");
                        if(picList != null) {
                            num = picList.size();
                        } else {
                            LogUtils.e("一题超过两个格子，却返回null");
                        }
                    }
                    String fileName = item2.getQuestionId().intValue() + "_" + num;
                    String filePath = FileUtils.getPicFilePath(this, pDir + File.separator + "t", "" + fileName, "");
                    FileUtils.saveBitmap(clip_bitmap, filePath);
                    if(num > 0) {
                        picStr = picStr + "," + filePath;
                    } else {
                        picStr = filePath;
                    }
                    qId_pic.put(item2.getQuestionId().intValue(), picStr);
                }
            }
        }

        //将小图上传阿里云
        oss_qId_pic.clear();
        mIsSubmiting = true;
        List<AssistantQuestion> qlist = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            qlist = exam.getQuestionList();
        } else {
            qlist = DBUtils.getInstance(this).getAssistantQuestionByAssistantExamId(exam.getId());
        }
        for(AssistantQuestion item : qlist) {
            if(QuestionTypeUtil.isSubjectQuestion(item.getQuestionType())) {
                String picStr = qId_pic.get(item.getQuestionId().intValue());
                List<String> picList = StringUtil.strToList(picStr, ",");
                if(picList == null || picList.size() == 0) {
                    LogUtils.e("这一题主观题没有找到截图");
                } else {
                    if(mMoudle == TsdService.MODULE_SMALLTEST_DOT && picList.size() > 1) {
                        //小测中有两张图片要合并
                        Bitmap bitmap_all = null;
                        for(String filePath : picList) {
                            File f_com = new File(filePath);
                            if(f_com.exists()) {
                                FileInputStream fis = null;
                                try {
                                    fis = new FileInputStream(filePath);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                Bitmap bitmap_com  = BitmapFactory.decodeStream(fis);
                                if(bitmap_all == null) {
                                    bitmap_all = bitmap_com;
                                } else {
                                    bitmap_all = BitmapUtil.combineBitmap_tb(bitmap_all, bitmap_com);
                                }
                            }
                        }
                        if(bitmap_all == null) {
                            break;
                        }

                        String fileName = item.getQuestionId().intValue() + "_com";
                        String filePath = FileUtils.getPicFilePath(this, pDir + File.separator + "t", "" + fileName, "");
                        FileUtils.saveBitmap(bitmap_all, filePath);

                        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
                        final String uploadFileName = "0" + TsdService.str_teacher_index_split + studentId + "_" + exam.getExamId() + "_" + item.getQuestionId().intValue() + "_"  + System.currentTimeMillis() + ".png";
                        File file = new File(filePath);
                        if(file.exists()) {
                            mOssCount++;
                            OssParams ossParams = new OssParams(item.getQuestionId(), null, uploadFileName, filePath);
                            mOssParamsList.add(ossParams);
                            //UploadOss.getInstance().upload2OSS(uploadFileName, filePath, ossUploadListener, ossParams);
                        }

                    } else {
                        for(String filePath : picList) {
                            String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
                            int lastIndex_start = filePath.lastIndexOf(File.separator);
                            int lastIndex_end = filePath.lastIndexOf(".");
                            String strLast = filePath.substring(lastIndex_start + 1, lastIndex_end);
                            List<String> lastList = StringUtil.strToList(strLast, "_");
                            if(lastList == null || lastList.size() != 2) {
                                LogUtils.e("解析文件路径的参数有问题");
                            }
                            final String uploadFileName = lastList.get(1) + TsdService.str_teacher_index_split + studentId + "_" + exam.getExamId() + "_" + lastList.get(0) + "_"  + System.currentTimeMillis() + ".png";
                            File file = new File(filePath);
                            if(file.exists()) {
                                mOssCount++;
                                OssParams ossParams = new OssParams(item.getQuestionId(), null, uploadFileName, filePath);
                                mOssParamsList.add(ossParams);
                                //UploadOss.getInstance().upload2OSS(uploadFileName, filePath, ossUploadListener, ossParams);
                            }
                        }
                    }
                }
            }
        }
        osssUploadByOssCount();
        isOssSuccess();
    }

    private boolean subjectHavMyAns(int exmaId, boolean isMyAns) {
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            return isMyAns;
        } else {
            List<PenOffLineGridInfo> penOffLineGridInfoList = DBUtils.getInstance(this).getPenOffLineGridInfoByExamId(exmaId);
            if(penOffLineGridInfoList != null  && penOffLineGridInfoList.size() > 0) {
                //离线在线同步用, 默认主观题都有作答
                return true;
            }
            return isMyAns;
        }
    }

    private void osssUploadByOssCount() {
        if(mOssCount > 0) {
            OssParams params = mOssParamsList.get(mOssParamsList.size() - mOssCount);
            UploadOss.getInstance().upload2OSS(params.getUploadFileName(), params.getFilePath(), ossUploadListener, params);
        }
    }

    private void isOssSuccess() {
        LogUtils.i("m1: isOssSuccess: mOssCount=" + mOssCount + ", mIssubmitSuccess=" + mIsSubmitSuccess);
        if(mOssCount == 0 && mIsSubmitSuccess) {
            if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                submitData_pre_smallTest();
            } else {
                submitData_pre();
            }

        } else {
            isSubmitSuccess();
        }
    }

    private void isSubmitSuccess() {
        if(mOssCount == 0 && mIsSubmitSuccess) {
            //弹提示框，提交成功
            if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                ToastUtil.initToast("提交作业成功");
            }
        } else if(!mIsSubmitSuccess){
            mIsSubmitSuccess = true;
            DialogXUtil.waitDialogDismiss();
            //弹提示框，提交失败
            ToastUtil.initToast("提交作业失败，请重新提交~");
        }
    }

    UploadOss.OnUploadListener ossUploadListener = new UploadOss.OnUploadListener() {
        @Override
        public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
            LogUtils.i("m1:-----ossUploadListener uploadSuccess threadName: "+Thread.currentThread().getName());
            saveOssPathToDb(ossParams, uploadFile);
            mOssCount--;
            isOssSuccess();
            osssUploadByOssCount();
            return null;
        }

        @Override
        public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
            LogUtils.i("m1:-----ossUploadListener uploadSuccess threadName: "+Thread.currentThread().getName());
            mOssCount--;
            mIsSubmitSuccess = false;
            DialogXUtil.waitDialogDismiss();
            isOssSuccess();
            if("-1".equals(uploadFile)) {
                delayToOutLogin();
            }
            return null;
        }
    };

    private void saveOssPathToDb(OssParams ossParams, String uploadFile) {
        int questionId = (int)ossParams.getId();
        String picStr = "";
        if(oss_qId_pic.containsKey(questionId)) {
            picStr = oss_qId_pic.get(questionId);
            if(picStr != null) {
                picStr = picStr + "," + uploadFile;
            } else {
                picStr = uploadFile;
            }
        } else {
            picStr = uploadFile;
        }
        oss_qId_pic.put(questionId, picStr);
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            for(AssistantQuestion q : mSmallTestData.getQuestionList()) {
                if(q.getQuestionId().intValue() == questionId) {
                    AssistantQuestion question = q;
                    question.setOssPath(picStr);
                    break;
                }
            }
        } else {
            AssistantQuestion question = DBUtils.getInstance(this).getAssistantQuestionByQuestionId(questionId);
            if(question == null) {
                return;
            }
            question.setOssPath(picStr);
            DBUtils.getInstance(this).updateAssistantQuestion(question);
        }
    }

    private int getNoAnswerNum() {
        int num = 0;
        if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
            for(AssistantQuestion item : mSmallTestData.getQuestionList()) {
                if(QuestionTypeUtil.isSubjectQuestion(item.getQuestionType())) {
                    if(!item.getIsSubjectMyAns()) {
                        num++;
                    }
                } else {
                    if (StringUtil.isEmpty(item.getMyAnswer())) {
                        num++;
                    }
                }
            }
        } else {
            AssistantExam exam = DBUtils.getInstance(this).getAssistantExamByExamId(mCurExam.getExamId());
            if(exam != null) {
                List<PenOffLineGridInfo> penOffLineGridInfoList = DBUtils.getInstance(this).getPenOffLineGridInfoByExamId(exam.getExamId());
                if(penOffLineGridInfoList != null  && penOffLineGridInfoList.size() > 0) {
                    //离线在线同步用
                    return 0;
                }

                for(AssistantQuestion item : exam.getQuestionList()) {
                    if(QuestionTypeUtil.isSubjectQuestion(item.getQuestionType())) {
                        if(!item.getIsSubjectMyAns()) {
                            num++;
                        }
                    } else {
                        if(StringUtil.isEmpty(item.getMyAnswer())) {
                            num++;
                        }
                    }
                }
            }
        }
        return num;
    }

    private void showNoPenConnectDialog(boolean isAgain) {
        String mac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
        if(StringUtil.isEmpty(mac) || isAgain) {
            DialogXUtil.customDialogShow(isAgain ? "自动重连失败！" : "智能笔连接未连接！\r\n请连接智能笔后再作答", "", "手动连接", true, new DialogXUtil.OnDialogXListen() {
                @Override
                public void onListenDialogOk() {

                }

                @Override
                public void onListenDialogCancel() {
                    //手动连接
                    ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                }

                @Override
                public void onListenDialogClose() {

                }
            });
        } else {
            DialogXUtil.customDialogShow("智能笔连接未连接！\r\n请连接智能笔后再作答", "刷新自动重连", "手动连接", new DialogXUtil.OnDialogXListen() {
                @Override
                public void onListenDialogOk() {
                    //自动连接
                    mIsPenAutoConnect = true;
                    DialogXUtil.waitDialogShow("正在自动连接智能笔...");
                    mTsdServiceBinder.on_startScan();
                }

                @Override
                public void onListenDialogCancel() {
                    //手动连接
                    ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                }

                @Override
                public void onListenDialogClose() {

                }
            });
        }
    }


    private void initSmallTestData(GetAssistantQuestionList resp_data) {
        mIsClickable = true;
        mSmallTestData = new AssistantExam(null, resp_data.getExamId(), resp_data.getExamName(), resp_data.getPublishId(), ComUtil.getStringDate(), null);
        List<AssistantQuestion> questionList = new ArrayList<>();
        List<PagePicture> pagePictureList = new ArrayList<>();
        Map<Integer, PagePicture> picId_page = new HashMap<>();

        for(GetAssistantQuestionList2 questinInfo : resp_data.getQuestionList()) {
            AssistantQuestion smallTest_question = new AssistantQuestion(null, questinInfo.getQuestionId(), questinInfo.getQuestionNo(),
                    questinInfo.getQuestionScore(), questinInfo.getQuestionContent(),
                    questinInfo.getQuestion(), StringUtil.strlistToString(questinInfo.getOptions(), "###"),
                    questinInfo.getExplain(), StringUtil.strlistToString(questinInfo.getAnswers(), "###"),
                    questinInfo.getQuestionType(), questinInfo.getIsSingle(),
                    questinInfo.getQuestionScreen(), questinInfo.getScreenType(), questinInfo.getScreenId(),
                    questinInfo.getListeningUrl(), questinInfo.getDuration(), questinInfo.getChapterId(),
                    questinInfo.getQuestionDetailId(), null, null,  false, null);
            questionList.add(smallTest_question);

            if(questinInfo.getGridsVoList() == null || questinInfo.getGridsVoList().size() == 0) {
                if(!mIsGridNull) {
                    mIsGridNull = true;
                    ToastUtil.initToast("获取格子出错");
                }
                mSmallTestData = null;
                mIsPenMoveOk = false;
                tv_no_data.setText("获取的题目的格子数据为空~");
                showNoData(true);
                return;
            } else if(questinInfo.getGridsVoList().get(0).getPageserial() == null){
                if(!mIsGridNull) {
                    mIsGridNull = true;
                    ToastUtil.initToast("不是云蝶的码源");
                }
                mSmallTestData = null;
                mIsPenMoveOk = false;
                tv_no_data.setText("这套小测试题的使用的不是云蝶码源~");
                showNoData(true);
                return;
            }

            for (GetAssistantQuestionList_grids grid : questinInfo.getGridsVoList()) {
                if (picId_page.containsKey(grid.getPictureId().intValue())) {
                    PagePicture pagePicture = picId_page.get(grid.getPictureId().intValue());
                    PagePictureGrid pagePictureGrid = new PagePictureGrid(null, questinInfo.getQuestionId(), questinInfo.getQuestionNo(), grid.getStartX(), grid.getStartY(), grid.getEndX(), grid.getEndY(), questinInfo.getQuestionType(), null);
                    pagePicture.getGridList().add(pagePictureGrid);
                    picId_page.put(pagePicture.getPictureId().intValue(), pagePicture);
                } else {
                    PagePicture pagePicture = new PagePicture(null, grid.getPictureUrl(), grid.getBigPicWidth(), grid.getBigPicHeight(),
                            grid.getPictureId(), grid.getBookId(), grid.getPageNumber(), grid.getSectionNo(), grid.getOwnerNo(),
                            grid.getPageserial(), false, true, null, null, null, null,
                            null, null, null, null, null, 1, null);

                    List<PagePictureGrid> gridList = new ArrayList<>();
                    PagePictureGrid pagePictureGrid = new PagePictureGrid(null, questinInfo.getQuestionId(), questinInfo.getQuestionNo(), grid.getStartX(), grid.getStartY(), grid.getEndX(), grid.getEndY(), questinInfo.getQuestionType(), null);
                    gridList.add(pagePictureGrid);
                    pagePicture.setGridList(gridList);
                    picId_page.put(pagePicture.getPictureId().intValue(), pagePicture);
                }
            }
        }

        //Set<Integer> sets = picId_page.keySet();
        Iterator iter = picId_page.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            PagePicture val = (PagePicture)entry.getValue();
            pagePictureList.add(val);
        }
        mSmallTestData.setPictureList(pagePictureList);
        mSmallTestData.setQuestionList(questionList);

        initExam_smallTest();
        //switchPicData_real_pre_smallTest();
    }

    private void analysisDots_smallTest() {
        if(mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            mSmallTest_isGoodDot = false;
            if(mCurDot.pageAddress.equals(mSmallTestData.getPictureList().get(mSmallTest_picture_index).getPageserial())) {
                mSmallTest_isGoodDot = true;
                //判断是否切换题目
                switchQuestion_smallTest();
            } else {
                for(int i = 0; i < mSmallTestData.getPictureList().size(); i++) {
                    if(mCurDot.pageAddress.equals(mSmallTestData.getPictureList().get(i).getPageserial())) {
                        mSmallTest_picture_index = i;
                        mSmallTest_question_index = -1;
                        //mSmallTest_isGoodDot = true;
                        //mSmallTest_isGoodDot = true;//2021-11-15
                        //一定切换图片
                        switchPicData_smallTest();
                        break;
                    }
                }
            }
        } else {
            if(!mSmallTest_isGoodDot) {
                LogUtils.e("m1: 丢弃的移动或弹起点1");
            } else {
                //绘制图片
                drawBitmap_smallTest();
            }
        }
    }
    private void switchPicData_smallTest() {
        mIsSwitchBitmaping = true;
        if(mIsSaveingPic) {
            return;
        }
        DialogXUtil.waitDialogShow("正在切换图片，请稍后~");
        if(mGraffitiView != null) {
            mDoodleSaveType = DOODLE_SAVE_TYPE_SWITCH;
            mGraffitiView.save();
        }else {
            switchQuestion_smallTest();
            switchBitmap_smallTest();
        }
    }

    private void initExam_smallTest() {
        tv_title.setText(mSmallTestData.getExamName() == null ? "" : StringUtil.replaceAmp(mSmallTestData.getExamName()));
        initQuestionNumShow();

        switchPicData_smallTest();

    }

    private void switchQuestion_smallTest() {
        //判断是否切换题号
        boolean isSwich = false;
        if(mSmallTest_question_index == -1 && mSmallTest_picture_index == -1) {
            //第一次进入
            mSmallTest_question_index = 0;
            int questionId = mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionId();
            for(int i = 0; i < mSmallTestData.getPictureList().size(); i++) {
                for(int j = 0; j < mSmallTestData.getPictureList().get(i).getGridList().size(); j++) {
                    if(mSmallTestData.getPictureList().get(i).getGridList().get(j).getQuestionId().intValue() == questionId) {
                        mSmallTest_picture_index = i;
                        mSmallTest_pictureGrid_index = j;
                        break;
                    }
                }
                if(mSmallTest_picture_index != -1) {
                    break;
                }
            }
            isSwich = true;
            setCurQuestion_smallTest();
        } else if(mSmallTest_question_index == -1){
            //蓝牙笔点击切换图片，已经知道了图片的下标，要找到题目的下标
            int questionId = -1;
            int gridIndex = -1;
            int questinFirstId = -1;//如果点击题外了，找到这个id
            int gridFirstIndex = -1;
            for(PagePicture pagePicture : mSmallTestData.getPictureList()) {
                for(int j = 0; j < pagePicture.getGridList().size(); j++) {
                    PagePictureGrid grid = pagePicture.getGridList().get(j);
                    if(questinFirstId == -1 && mCurDot.pageAddress.equals(pagePicture.getPageserial())) {
                        questinFirstId = grid.getQuestionId().intValue();
                        gridFirstIndex = j;
                    }
                    //2021-11-15
                    if(!mCurDot.pageAddress.equals(pagePicture.getPageserial())) {
                        break;
                    }
                    float x = TsdPenUtil.getRealX(mCurDot.coordX, pagePicture.getBigPicWidth());
                    float y = TsdPenUtil.getRealY(mCurDot.coordY, pagePicture.getBigPicHeight());
                    if(x > grid.getStartX().floatValue() && x < grid.getEndX().floatValue() && y > grid.getStartY().floatValue() && y < grid.getEndY().floatValue()) {
                        questionId = grid.getQuestionId().intValue();
                        gridIndex = j;
                        break;
                    }
                }
                if(questionId != -1) {
                    break;
                }
            }
            if(questionId == -1) {
                //没有找到这一题，点击到题目外了，默认这一页的第一题
                questionId = questinFirstId;
                gridIndex = gridFirstIndex;
            }

            for(int i = 0; i < mSmallTestData.getQuestionList().size(); i++) {
                if(questionId == mSmallTestData.getQuestionList().get(i).getQuestionId().intValue()) {
                    mSmallTest_question_index = i;
                    mSmallTest_pictureGrid_index = gridIndex;
                    break;
                }
            }

            if(mSmallTest_question_index == -1) {
                LogUtils.e("没有找到这一题，出错了");
                return;
            }

            isSwich = true;
            setCurQuestion_smallTest();

        } else if(mSmallTest_picture_index == -1) {
            //手指点击tab 切题， 已经知道题目的下标，找到图片的下标
            for(int i = 0; i < mSmallTestData.getPictureList().size(); i++) {
                for(int j = 0; j < mSmallTestData.getPictureList().get(i).getGridList().size(); j++) {
                    if(mSmallTestData.getPictureList().get(i).getGridList().get(j).getQuestionId().intValue() == mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionId().intValue()) {
                        mSmallTest_picture_index = i;
                        mSmallTest_pictureGrid_index = j;
                        break;
                    }
                }

                if(mSmallTest_picture_index != -1) {
                    break;
                }
            }

            if(mSmallTest_picture_index_temp != mSmallTest_picture_index) {
                switchPicData_smallTest();
            } else {
                setCurQuestion_smallTest();
            }


        } else {
            //没有切图片，也没有点击切题，需要自己判断题目是否切换
            int questionId = -1;
            int gridIndex = -1;
            int questinFirstId = -1;//如果点击题外了，找到这个id
            int gridFirstIndex = -1;
            for(PagePicture pagePicture : mSmallTestData.getPictureList()) {
                for(int j = 0; j < pagePicture.getGridList().size(); j++) {
                    PagePictureGrid grid = pagePicture.getGridList().get(j);
                    if(questinFirstId == -1 && mCurDot.pageAddress.equals(pagePicture.getPageserial())) {
                        questinFirstId = grid.getQuestionId().intValue();
                        gridFirstIndex = j;
                    }
                    float x = TsdPenUtil.getRealX(mCurDot.coordX, pagePicture.getBigPicWidth());
                    float y = TsdPenUtil.getRealY(mCurDot.coordY, pagePicture.getBigPicHeight());
                    if(mCurDot.pageAddress.equals(pagePicture.getPageserial()) && x > grid.getStartX().floatValue() && x < grid.getEndX().floatValue() && y > grid.getStartY().floatValue() && y < grid.getEndY().floatValue()) {
                        questionId = grid.getQuestionId().intValue();
                        gridIndex = j;
                        break;
                    }
                }
                if(questionId != -1) {
                    break;
                }
            }

            if(questionId == -1) {
                //没有找到这一题，点击到题目外了，默认这一页的第一题
                questionId = questinFirstId;
                gridIndex = gridFirstIndex;
            }

            for(int i = 0; i < mSmallTestData.getQuestionList().size(); i++) {
                if(questionId == mSmallTestData.getQuestionList().get(i).getQuestionId().intValue()) {
                    if(mSmallTest_question_index != i) {
                        mSmallTest_question_index = i;
                        mSmallTest_pictureGrid_index = gridIndex;
                        isSwich = true;
                        setCurQuestion_smallTest();
                    }
                    break;
                }
            }
        }
        if(!isSwich) {
            //不需要切题，直接绘制
            drawBitmap_smallTest();
        }
    }

    private void setCurQuestion_smallTest() {
        LogUtils.i("m1: 切换题号");
        if(QuestionTypeUtil.isSubjectQuestion(mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionType())) {
            //mSmallTestData.getQuestionList().get(mSmallTest_question_index).setMyAnswer("1"); //主观题设置1，认为这一题已经作答
            if(mTsdServiceBinder.on_getmBleDevice() == null) {
                showNoPenConnectDialog(false);
            }
        }
        mHomeworkNumAdapter.setmQuestionId(mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionId().intValue());
        if(QuestionTypeUtil.isObjectQuestion(mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionType())) {
            rv_object.setVisibility(View.VISIBLE);
            fl_doodle.setVisibility(View.INVISIBLE);
        } else {
            rv_object.setVisibility(View.GONE);
            fl_doodle.setVisibility(View.INVISIBLE);
        }

        if(!mIsSwitchBitmaping) {
            //没有切图片直接滚动图片
            scrollBitmap_smallTest();
            //滚动完图片后绘制图片
            drawBitmap_smallTest();
        } else {
            LogUtils.i("m1: 正在切换图片，等切换图片后再滚动图片");
        }
    }

    private void switchBitmap_smallTest() {
        downLoadImg();
    }

    private void scrollBitmap_smallTest() {
        if(mSmallTest_picture_index >= mSmallTestData.getPictureList().size()) {
            LogUtils.e("scrollBitmap_smallTest 越界异常，mSmallTest_picture_index");
            return;
        }
        if(mSmallTest_pictureGrid_index >= mSmallTestData.getPictureList().get(mSmallTest_picture_index).getGridList().size()) {
            LogUtils.e("scrollBitmap_smallTest 越界异常，mSmallTest_pictureGrid_index");
            return;
        }

        PagePictureGrid grid = mSmallTestData.getPictureList().get(mSmallTest_picture_index).getGridList().get(mSmallTest_pictureGrid_index);
        m_tran_x = grid.getStartX().floatValue();
        m_tran_y = grid.getStartY().floatValue();
        m_tran_again_x = 0;
        m_tran_again_y = 0;
        mTemp_w = grid.getEndX().floatValue() - grid.getStartX().floatValue();
        mTemp_h = grid.getEndY().floatValue() - grid.getStartY().floatValue();
        mIsTran_x = false;
        mIsTran_y = false;
        if(mTemp_w > fl_doodle.getWidth()) {
            mIsTran_x = true;
        }
        if(mTemp_h > fl_doodle.getHeight()) {
            mIsTran_y = true;
        }

        LogUtils.i("m1: 滚动坐标到x=" + m_tran_x + ", y = " + m_tran_y + ", mTemp_w = " + mTemp_w + ", mTemp_h = " + mTemp_h);

        mGraffitiTouchGestureListener.setGraffitiTranslationXY(-m_tran_x, -m_tran_y);

        mGraffitiView.refreshMaskView(mTemp_w, mTemp_h, mGraffitiView.getWidth(), mGraffitiView.getHeight());


        if(QuestionTypeUtil.isObjectQuestion(mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionType())) {
            rv_object.setVisibility(View.VISIBLE);
            fl_doodle.setVisibility(View.INVISIBLE);
        } else {
            rv_object.setVisibility(View.GONE);
            fl_doodle.setVisibility(View.VISIBLE);
        }

    }
    private void drawBitmap_smallTest() {
        drawBitmap();
    }

    private void clickChoiceQuestion_smallTest(AssistantQuestion question) {
        for(PagePicture item : mSmallTestData.getPictureList()) {
            for(PagePictureGrid item2 : item.getGridList()) {
                if(item2.getQuestionId().intValue() == question.getQuestionId().intValue()) {
                    float d_x = TsdPenUtil.picToDotX(item2.getStartX().floatValue() + 5, item.getBigPicWidth().intValue());
                    float d_y = TsdPenUtil.picToDotY(item2.getStartY().floatValue() + 5,  item.getBigPicHeight().intValue());
                    LogUtils.i("格子坐标转成纸的dot坐标: x:" + d_x + ", y:" +d_y);
                    CoordinateInfo ci_down = new CoordinateInfo(TsdService.PEN_DOWN_MESSAGE, item.getPageserial(), (int)d_x, (int)d_y, 0, 0, 0, false, 0, 0);
                    CoordinateInfo ci_up = new CoordinateInfo(TsdService.PEN_UP_MESSAGE, item.getPageserial(), (int)d_x, (int)d_y, 0, 0, 0, false, 0, 0);
                    mOffLineDots.offer(ci_down);
                    mOffLineDots.offer(ci_up);
                    nextDots();
                    return;
                }
            }
        }
    }

    private void submitData_pre_smallTest() {
        if(mTsdServiceBinder == null) {
            LogUtils.e("mTsdServiceBinder == null");
            return;
        }
        if(mTsdServiceBinder.on_getmStudentJoinRoom_command() == null) {
            LogUtils.e("mTsdServiceBinder.on_getmStudentJoinRoom_command() == null");
            return;
        }
        if(mTsdServiceBinder.on_getmSmallTest_command() == null) {
            LogUtils.e("mTsdServiceBinder.on_getmSmallTest_command() == null");
            return;
        }
        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        SmallTestCommitReq req = new SmallTestCommitReq();
        AssistantExam exam = mSmallTestData;
        //req.setInstructions(mTsdServiceBinder.on_getmStudentJoinRoom_command().getInstructions());
        req.setInstructions("studentCommitExam");
        req.setId(studentId);
        req.setRoomId(mTsdServiceBinder.on_getmStudentJoinRoom_command().getRoomId());
        req.setBeginTime(exam.getBeginTime());
        req.setFinishTime(ComUtil.getStringDate());
        req.setExamId(mSmallTestData.getExamId());
        req.setPublishId(mTsdServiceBinder.on_getmSmallTest_command().getPublishId());
        //req.setIsLine(mTsdServiceBinder.on_getmSmallTest_command().getIsLine());
        req.setIsLine(1);
        List<SmallTestCommitReq_questionList> qList = new ArrayList<>();
        for(AssistantQuestion item : exam.getQuestionList()) {
            SmallTestCommitReq_questionList vo = new SmallTestCommitReq_questionList();
            if(QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                vo.setAnswerType(1);
                vo.setAnswerContent(item.getMyAnswer());
            } else {
                vo.setAnswerType(2);
                vo.setAnswerContent(item.getOssPath());
            }
            vo.setQuestionId(item.getQuestionId());
            vo.setQuestionType(item.getQuestionType());
            qList.add(vo);
        }
        req.setQuestionList(qList);
        String json = JsonUtils.toJson(req);

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_WEBSOCKE_SMALLTEST_COMMIT, JsonUtils.toJson(req)));
        mTsdServiceBinder.on_setmModule(TsdService.MODULE_ROOM);
        deleteDataAndFile();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        LogUtils.i("m1: bus-->" + messageEvent.toString());
        int action = messageEvent.getAction();
        String msg = messageEvent.getMsg();
        if(action == EventBusMessage.EVENT_BUS_ACTION_PEN_CONNECT_IS){
            if(!mIsPenAutoConnect) {
                if("已连接".equals(msg)) {

                } else if("未连接".equals(msg)) {
                    if(mMoudle == TsdService.MODULE_SMALLTEST_DOT) {
                        if(QuestionTypeUtil.isSubjectQuestion(mSmallTestData.getQuestionList().get(mSmallTest_question_index).getQuestionType())) {
                            showNoPenConnectDialog(false);
                        }
                    } else {
                        if(QuestionTypeUtil.isSubjectQuestion(mCurQuestion.getQuestionType())) {
                            showNoPenConnectDialog(false);
                        }
                    }
                }
            }
        }
    }
}
